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
Uncaught TypeError: Cannot set property 'className' of null
提问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 className
call in an if
block:
它失败是因为没有 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.currentPage
is set in JavaScript, and the HTML on which it is acting.
否则,您将需要发布更多代码来向我们展示this.currentPage
JavaScript 中的位置,以及它所作用的 HTML。
回答by Nicolae Albu
oldPageAnchor
or newPageAnchor
is null because the element with your specified ID is not found. Check that this.currentPage
has your desired value AND that the elements that you are trying to find are on the HTML page you're on.
oldPageAnchor
ornewPageAnchor
为空,因为未找到具有您指定 ID 的元素。检查是否this.currentPage
具有您想要的值以及您尝试查找的元素是否位于您所在的 HTML 页面上。