“无法在javascript中设置属性'onclick'of null”

问题描述 投票:-1回答:2

我有一个问题,当使用addEventListeneronclick代码没有执行但典型的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>
javascript onclick onclicklistener
2个回答
0
投票
var IDs = ('general-edit-container', 'contloc', 'payment', 'attach', 'course');

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

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

目前还不清楚你的count函数是如何实现的,但你可以简单地使用它来代替使用它

var number = IDs.length;

0
投票

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

  • 添加了检查元素是否实际存在的信息
  • 转换数组使用方括号
  • 将计数更改为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>
© www.soinside.com 2019 - 2024. All rights reserved.