Javascript 未捕获的类型错误:无法将属性“className”设置为 null

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6733660/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 22:57:33  来源:igfitidea点击:

Uncaught TypeError: Cannot set property 'className' of null

javascript

提问by chella

I am using js file for paginate a table. It occurs an error while I am trying to click on next page button. It just show the error like this "Uncaught TypeError: Cannot set property 'className' of null".

我正在使用 js 文件对表格进行分页。当我尝试单击下一页按钮时发生错误。它只是显示这样的错误“未捕获的类型错误:无法设置 null 的属性 'className'”。

Here is my code:

这是我的代码:

    var oldPageAnchor = document.getElementById('pg'+this.currentPage);
    oldPageAnchor.className = 'pg-normal';
    this.currentPage = pageNumber;
    var newPageAnchor = document.getElementById('pg'+this.currentPage);
    newPageAnchor.className = 'pg-selected'; 

回答by Michael Berkowski

It fails because there is no DOM element with the id 'pg'+this.currentPage. If this is normal behavior, then you can just wrap the classNamecall in an ifblock:

它失败是因为没有 id 的 DOM 元素'pg'+this.currentPage。如果这是正常行为,那么您可以将className调用包装在一个if块中:

var oldPageAnchor = document.getElementById('pg'+this.currentPage);
if (oldPageAnchor) {
   oldPageAnchor.className = 'pg-normal';
}

Otherwise, you'll need to post more code to show us where this.currentPageis set in JavaScript, and the HTML on which it is acting.

否则,您将需要发布更多代码来向我们展示this.currentPageJavaScript 中的位置,以及它所作用的 HTML。

回答by Nicolae Albu

oldPageAnchoror newPageAnchoris null because the element with your specified ID is not found. Check that this.currentPagehas your desired value AND that the elements that you are trying to find are on the HTML page you're on.

oldPageAnchorornewPageAnchor为空,因为未找到具有您指定 ID 的元素。检查是否this.currentPage具有您想要的值以及您尝试查找的元素是否位于您所在的 HTML 页面上。