我试图在单击复选框时添加一个输入字段,并且希望选中该复选框(这是其默认行为!),但是即使在输入字段出现后也没有选中该复选框。以下是我的带JavaScript的HTML代码。
function check_test() {
if (document.contains(document.getElementById("test_input"))) {
document.getElementById("test_input").remove();
}
document.getElementById("test_div").innerHTML += "<input type='text' name='test_input' id='test_input'/>";
}
<div id="test_div">
<input type="checkbox" name="test_checkbox" id="test_checkbox" onclick="check_test()" />
</div>
我也在JsFiddle中尝试了此操作,它给出了相同的错误,并且不确定我在做什么错。
您有条件地删除#test_input
DOM中是否存在,但else
添加时就没有使用。因此,无论您处于哪种状态,都必须在将输入添加到DOM的情况下结束该函数。
正如其他人提到的那样,当您+=
使用innerHTML时,实际上是在创建一个全新的字符串,从而将原始复选框重新初始化为未选中状态。
您可能只想在包装器上附加一个新的孩子。我也改用了该onchange
事件,因此无论单击还是以编程方式选中该框,它都将执行您想要的操作。
function check_test(checkbox) {
const checked = checkbox.checked; // is it checked?
const testInput = document.getElementById("test_input"); // test_input element
// if it's checked and doesn't have an input, add it
if (checked && !testInput) {
const newInput = document.createElement('input');
newInput.type = 'text';
newInput.name = 'test_input';
newInput.id = 'test_input';
checkbox.parentNode.appendChild(newInput);
}
// otherwise, if it's not checked and there is an input in the DOM, remove it
else if (!checked && testInput) {
document.getElementById("test_input").remove();
}
}
<div id="test_div">
<input type="checkbox" name="test_checkbox" id="test_checkbox" onchange="check_test(event.target)" />
</div>
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句