开发者问题收集

JavaScript 中“无法将属性‘onclick’设置为 null”

2019-03-21
64

我在使用 addEventListeneronclick 时遇到问题,代码未执行,但 html 标签中典型的 onclick 作为属性可以工作。

我在在线调试器中测试我的代码时发现的问题状态是

"Uncaught TypeError: Cannot set property 'onclick' of null.

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>
2个回答
var IDs = ('general-edit-container', 'contloc', 'payment', 'attach', 'course');

使用方括号创建数组,如下所示:

var IDs = ['general-edit-container', 'contloc', 'payment', 'attach', 'course'];

目前尚不清楚您的 count 函数是如何实现的,但您可以简单地执行此操作,而不是使用它

var number = IDs.length;
Yiin
2019-03-21

这应该可以帮助您调试问题。

  • 添加了元素是否实际存在的检查
  • 将数组转换为使用方括号
  • 将计数更改为 Array.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>
Webber
2019-03-21