这是我类作业的一部分。它是一个小型网络应用程序。下面的代码部分是选择按钮(复选框)的功能。代码运行良好。
我的问题是我在控制台上收到此错误:
Uncaught TypeError: Cannot set property 'checked' of null
at selectGirls (indexj.js:163)
at HTMLAnchorElement.onclick (index.html:137)
我知道我会收到此错误,因为我并不是在每个页面上都有这些元素。为了澄清这一点,我的意思是第 1 页有两个复选框,但第 2 页有 5 个复选框,就像那样。
我想对所有页面使用同一个 JS 文件。我的问题是如何最好地避免这些控制台错误?我不想让他们从控制台隐藏作为解决方案。非常感谢您的意见。
function selectAllStudents() {
unselectAllStudents();
let boxes = $(".scores").toArray();
document.getElementById('check_Terrilyn').checked = true;
document.getElementById('check_Vinnie').checked = true;
document.getElementById('check_Boren').checked = true;
document.getElementById('check_Tempie').checked = true;
document.getElementById('check_Mapes').checked = true;
document.getElementById('check_Fletcher').checked = true;
document.getElementById('check_Bovee').checked = true;
document.getElementById('check_Figgs').checked = true;
}
最佳答案
最简单的就是检查它们是否存在
if (document.getElementById('check_Terrilyn'))
document.getElementById('check_Terrilyn').checked = true;
编辑
一个更现代的方法,假设有未知数量的复选框,可以使用 querySelectorAll
.
它将返回一个元素列表(NodeList),例如,正如您的代码所建议的那样,所有复选框的 id
都以 check_
开头,您可以使用它像这样与 attribute selector :
var els = document.querySelectorAll('[id^="check_"]');
els.forEach(function (el) {
el.checked = true;
});
<input id="check_0" type="checkbox" value="0">
<input id="check_1" type="checkbox" value="1">
<input id="check_2" type="checkbox" value="2">
<input id="check_3" type="checkbox" value="3">
关于javascript - JS检查getElementById是否存在,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49896227/