最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Cannot read property 'indexOf' of null - Stack Overflow

programmeradmin1浏览0评论

the code work but the console log show Cannot read property 'indexOf' of null

It cannot be seen in jsfiddle, btw here is the demo of what I want.

/

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').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();
    }
});

the code work but the console log show Cannot read property 'indexOf' of null

It cannot be seen in jsfiddle, btw here is the demo of what I want.

http://jsfiddle/cw6cgg27/

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').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();
    }
});
Share Improve this question asked Aug 14, 2014 at 1:17 user3836151user3836151 2313 gold badges5 silver badges11 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 2

It is plaining that nextSibling does not exist. You must code defensively.

$('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.

I think changing your code into this would work:

$('br').each(function () {
    console.log($(this).get(0).nextSibling.nodeValue.indexOf('作詞') > -1);
});
发布评论

评论列表(0)

  1. 暂无评论