第二个存在条件不起作用
Second exists condition does not work
我有一个关于javascript的问题,我有两个条件来检查输入字段是否存在。但它只是向我展示了"opleiding存在",而不是"opleiding存在"answers"domein存在"。
请告诉我我的代码出了什么问题。
非常感谢!
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Untitled Document</title>
<script type="text/javascript">
function submit()
{
var opleiding = document.getElementById("opleiding");
var domein = document.getElementById("domein");
if(document.getElementById("opleiding")){
document.write("opleiding exists");
}
if (document.getElementById("domein")){
document.write("domein exists");
}
}
</script>
</head>
<body>
<input type="hidden" id="domein" value="domein" />
<input type="hidden" id="opleiding" value="opleiding" />
<div id="button" onclick="submit()">
<strong>button text</strong>
</div>
</body>
</html>
document.write
将覆盖页面中的现有内容。这就是为什么你只在信息上看到的原因。
您必须使用document.body.appendChild
来显示这两条错误消息。
function submit()
{
var opleiding = document.getElementById("opleiding");
var domein = document.getElementById("domein");
var textElement;
if(document.getElementById("opleiding")){
textElement = document.createElement("p");
textElement.textContent = "opleiding exists";
document.querySelector("#results").appendChild(textElement);
}
if (document.getElementById("domein")){
textElement = document.createElement("p");
textElement.textContent = "domein exists";
document.querySelector("#results").appendChild(textElement);
}
}
<body>
<input type="hidden" id="domein" value="domein" />
<input type="hidden" id="opleiding" value="opleiding" />
<div id="results"></div>
<div id="button" onclick="submit()">
<strong>button text</strong>
</div>
</body>
您应该避免使用document.write
,因为这是一种不推荐使用的方法。当您第一次使用它时,它会写下您想要的内容,但会根据其定义删除页面的所有内容。
要想做你想做的事情,你应该使用document.body.appendChild
来"写"一些包含文本的元素(比如<div>
),或者向document.body.innerHTML
添加一些文本,这里有一个例子:
function submit() {
var opleiding_div = document.createElement('div'),
domein_div = document.createElement('div');
opleiding_div.textContent = "opleiding exists";
domein_div.textContent = "domein exists";
if(document.getElementById("opleiding")){
document.body.appendChild(opleiding_div);
}
if (document.getElementById("domein")){
document.body.appendChild(domein_div);
}
}
相关文章:
- Javascript,如果条件在没有&&逻辑运算符当&&它不起作用
- 淘汰赛.JS'启用'长度绑定条件不起作用
- 第二个存在条件不起作用
- 带有 AJAX 响应或 AJAX 响应的 IF 条件.响应.Text 不起作用
- 如果条件在代码点火器的模型中不起作用
- IE 8的条件注释不起作用
- 如果条件在JAVASCRIPT中不起作用
- Angular中的复选框条件类不起作用
- 快速键入时,Javascript onKeyUp条件不起作用
- 只有在条件满足时才加载javascript脚本-不起作用
- javascript if条件&&条件不'不起作用
- JQuery中的条件不起作用
- 默认条件在节点中不起作用
- 如果选中两个复选框,则条件在 jQuery 中不起作用
- if 语句在满足条件时不起作用
- Angularjs 多个“OR”条件不起作用
- 如果条件不起作用,则有类
- Window.open() 在 Multiple if 条件中不起作用
- 加载函数在满足 jQuery 中的 if 条件后不起作用
- Window.open 在包含确认对话框的 if 条件中不起作用