我正在 javascript Hide/show div on checkbox: checked/unchecked 使用 Javascript .
var elem = document.getElementById('powermail_fieldwrap_331'),
checkBox = document.getElementById('powermail_field_doruovaciaadresa2_1');
checkBox.checked = false;
checkBox.onchange = function doruc() {
elem.style.display = this.checked ? 'block' : 'none';
};
checkBox.onchange();
我更改了“checkBox.checked = false;”到“checkBox.checked = true;” 它无论如何都能工作,但会产生错误: 未捕获类型错误:无法将属性“检查”设置为 null
在这种情况下,我该如何修复这个错误?
谢谢。
最佳答案
fiddle 工作正常。唯一的问题可能是脚本在复选框成为 DOM 的一部分之前执行。
将代码包装在 onload
事件中。
window.onload = function() {
var elem = document.getElementById('powermail_fieldwrap_331'),
checkBox = document.getElementById('powermail_field_doruovaciaadresa2_1');
checkBox.checked = false;
checkBox.onchange = function doruc() {
elem.style.display = this.checked ? 'block' : 'none';
};
checkBox.onchange();
};
或者确保脚本标记写在复选框是 DOM 的一部分之后:
<label>
<input type="checkbox" id="powermail_field_doruovaciaadresa2_1" checked="checked" />
Show/hide
</label>
<div id="powermail_fieldwrap_331">Lorem ipsum</div>
<script>
var elem = document.getElementById('powermail_fieldwrap_331'),
checkBox = document.getElementById('powermail_field_doruovaciaadresa2_1');
checkBox.checked = true;
checkBox.onchange = function() {
elem.style.display = this.checked ? 'block' : 'none';
};
checkBox.onchange();
</script>
关于javascript - 未捕获的类型错误 : Cannot set property 'checked' of null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31634528/