第二个存在条件不起作用

Second exists condition does not work

本文关键字:不起作用 条件 存在 第二个      更新时间:2023-09-26

我有一个关于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);
    }
}