javascript 无法读取 null 的属性“indexOf”
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/25298629/
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
Cannot read property 'indexOf' of null
提问by user3836151
the code work but the console log show Cannot read property 'indexOf' of null
代码有效,但控制台日志显示无法读取 null 的属性“indexOf”
It cannot be seen in jsfiddle.net, btw here is the demo of what I want.
它在 jsfiddle.net 中看不到,顺便说一句,这里是我想要的演示。
because the markup suck, so I have to find every nodevalue of br, and get rip off line that start with 作詞, 作曲, 編曲, and 監製. It work but why in the console log there is an error?
因为标记很烂,所以我必须找到br的每个节点值,并从以作词,作曲,编曲和监制开始的下线。它工作但为什么在控制台日志中有错误?
$('br').each(function () {
if ((this.nextSibling.nodeValue.indexOf('作詞') > -1) || (this.nextSibling.nodeValue.indexOf('作曲') > -1) || (this.nextSibling.nodeValue.indexOf('編曲') > -1) || (this.nextSibling.nodeValue.indexOf('監製') > -1)) {
$(this.nextSibling).remove();
$(this).remove();
}
});
回答by Frambot
It is complaining that nextSibling
does not exist. You must code defensively.
这是抱怨nextSibling
不存在。你必须防御性地编码。
$('br').each(function () {
if (!this.nextSibling) {
return;
}
var nodeValue = this.nextSibling.nodeValue.trim();
var invalid = ['', '作詞', '作曲', '編曲', '監製'];
if (invalid.indexOf(nodeValue) !== -1) {
$(this.nextSibling).remove();
$(this).remove();
}
});
Note that my usage of Array.indexOf
exists for Internet Explorer 9+. So if you need to support IE8 you must use a polyfill or a different implementation.
请注意,我Array.indexOf
对 Internet Explorer 9+ 的使用存在。因此,如果您需要支持 IE8,则必须使用 polyfill 或其他实现。
回答by Bla...
I think changing your code into this would work:
我认为将您的代码更改为这样会起作用:
$('br').each(function () {
console.log($(this).get(0).nextSibling.nodeValue.indexOf('作詞') > -1);
});