2017-10-14 132 views
0

這裏是一段代碼,我在控制檯出現錯誤,任何人都可以指出我在哪裏做錯了?提前致謝。Uncaught TypeError:無法讀取未定義的屬性'nextSibling'

var intervalID = setInterval(function() { 
    // every 4 seconds execute following 
    var visibleWord = document.getElementsByClassName('visible')[0], 
    nextWord = visibleWord.nextSibling; 

    // check if nextSibling is textnode (whitespace) - if so get next next sibling. 
    if (nextWord.nodeType == 3) nextWord = nextWord.nextSibling; 

    // if there is a next node 
    if (!(nextWord == null)) { 
     visibleWord.setAttribute('class', 'hidden'); 
     nextWord.setAttribute('class', 'visible'); 
    } else { 
     clearInterval(intervalID); 
    } 
}, 4000) 
+0

檢查空訪問前/未定義nextSibling – awd

+0

_「檢查nextSibling是否爲textnode(空格) - 如果是這樣,請獲取下一個下一個兄弟」__> [.nextElementSibling](https://developer.mozilla.org/en-US/docs/Web/API/NonDocumentTypeChildNode/ nextElementSibling) – Andreas

回答

0

的錯誤意味着你正在尋找的元素(類visible)是不存在的代碼時跑了。也許你太早運行代碼(在DOM解析之前)。

嘗試添加簡單的,如果這樣的情況:

var visibleWord = document.getElementsByClassName('visible')[0]; 

if (!visibleWord) { 
    return; 
} 

// continue with the code... 
var nextWord = visibleWord.nextSibling; 
0

是指沒有visibleWord所以如果這是你可以返回,像這樣的情況:

var intervalID = setInterval(function() { 
// every 4 seconds execute following 
var visibleWord = document.getElementsByClassName('visible')[0], 
    if(null == visibleWord) { // added this line 
     return;     // and this line 
    }       // and this line 
    nextWord = visibleWord.nextSibling; 
// check if nextSibling is textnode (whitespace) - if so get next next sibling. 
if (nextWord.nodeType == 3) nextWord = nextWord.nextSibling; 
// if there is a next node 
if (!(nextWord == null)) { 
    visibleWord.setAttribute('class', 'hidden'); 
    nextWord.setAttribute('class', 'visible'); 
} else { 
    clearInterval(intervalID); 
} 
}, 4000) 
相關問題