2010-05-24 79 views
1

好吧,我試圖去處理JS中的nextSibling函數。這是我的問題在下面的代碼...nextSibling問題,應該很簡單

var fromRow = document.getElementById("row_1"); 

while(fromRow.nodeType == 1 && fromRow.nextSibling != null) 
{ 
    var fRowId = fromRow.id; 
    if (!fRowId) continue; 

    // THIS ONLY gets done once and alerts "row_1" ONLY :(
    alert(fRowId); 

    fromRow = fromRow.nextSibling; 
} 

好吧有人能告訴我這個代碼有什麼問題嗎?這個document.getElementById("row_1");元素旁邊有兄弟姐妹,因爲我可以看到它們,它們都具有id屬性,所以爲什麼它沒有得到兄弟姐妹的id屬性?我不明白。

row_1TR元素,我需要得到這個表中的TR元素在它旁邊,但由於某些原因,它只是變得我已經可以使用document.getElementById,arggg拿到1元。

謝謝你們:)

回答

2

嘗試:

var fromRow = document.getElementById("row_1"); 

while(fromRow !== null) 
{ 
    var fRowId = fromRow.id; 
    if (!fRowId || fromRow.nodeType != 1) { 
     fromRow = fromRow.nextSibling; 
     continue; 
    } 

    // THIS ONLY gets done once and alerts "row_1" ONLY :(
    alert(fRowId); 
    fromRow = fromRow.nextSibling; 
} 

雖然fromRow.nextSibling != null第二將停止以最後一次迭代,因爲你已經設置fromRownextSibling結尾。另外,如果下一個節點不是元素,則不一定要停止,如果可能的話,您只需要轉到下一個節點。最後,如果您在原始示例中點擊continue,則會遇到無限循環,因爲fromRow永遠不會更改值。

+0

謝謝你,這工作了魅力:) – SoLoGHoST 2010-05-24 22:16:38

+0

@SoLoGHoST:樂意幫助:-) – 2010-05-24 22:18:40

2

當while循環遇到不屬於1類型的節點時,while循環就會停止。因此,如果元素之間有任何空格,while循環將在第一個元素之後中斷。

你可能想要的是:

while(fromRow.nextSibling != null) 
{ 
    if(fromRow.nodeType == 1) { 
     ... 
    } 
} 
+0

也謝謝這個:-) – SoLoGHoST 2010-05-24 22:41:47