我有一个问题,当使用addEventListener
或onclick
代码没有执行但典型的onclick
作为html标签中的属性是有效的。
我在在线调试器中测试代码时发现的问题状态是
“未捕获的TypeError:无法设置null的属性'onclick'。
function classChange(sectionName, liName) {
var IDs = ('general-edit-container', 'contloc', 'payment', 'attach', 'course');
var number = count(IDs);
for (var i = 0; i < number; i++) {
if (IDs[i] == sectionName) {
document.getElementById(sectionName).style.display = "block";
} else {
document.getElementById(sectionName).style.display = "none";
}
}
var arr = ('one', 'two', 'three', 'four', 'five');
var num = count(arr);
for (var b = 0; b < num; b++) {
if (arr[b] == liName) {
document.getElementById(liName).className = " activebtn";
} else {
document.getElementById(liName).className = "";
}
}
}
window.onload = function() {
document.getElementById('geneBtn').onclick = function() {
classChange('general-edit-container', 'one');
alert('done');
};
}
<li id="one">
<a href="javascript:void(0);" id="geneBtn">
<img width="40px" src="img/person-info.png">
<h1 id="demo">General Information</h1>
</a>
</li>
var IDs = ('general-edit-container', 'contloc', 'payment', 'attach', 'course');
使用方括号创建数组,如下所示:
var IDs = ['general-edit-container', 'contloc', 'payment', 'attach', 'course'];
目前还不清楚你的count
函数是如何实现的,但你可以简单地使用它来代替使用它
var number = IDs.length;
这应该可以帮助您调试问题。
function classChange(sectionName, liName) {
var IDs = ['general-edit-container', 'contloc', 'payment', 'attach', 'course'];
var number = IDs.length;
for (var i = 0; i < number; i++) {
var section = document.getElementById(IDs[i]);
if (section === null) {
alert('There is no element with the id of "' + IDs[i] + '" in the DOM.');
continue;
}
if (IDs[i] == sectionName) {
section.style.display = "block";
} else {
section.style.display = "none";
}
}
var arr = ['one', 'two', 'three', 'four', 'five'];
var num = arr.length;
for (var b = 0; b < num; b++) {
var listItem = document.getElementById(arr[b])
if (listItem === null) {
alert('There is no element with the id of "' + arr[b] + '" in the DOM.');
continue;
}
if (arr[b] == liName) {
listItem.className = " activebtn";
} else {
listItem.className = "";
}
}
}
window.onload = function() {
document.getElementById('geneBtn').onclick = function() {
classChange('general-edit-container', 'one');
alert('done');
};
}
<li id="one">
<a href="javascript:void(0);" id="geneBtn">
<img width="40px" src="img/person-info.png">
<h1 id="demo">General Information</h1>
</a>
</li>