2013-02-25 25 views
3

我試圖做一個簡單的循環,並檢查節點/ parentNode類名稱是否匹配數組中的字符串。代碼如下:While循環與節點和parentNode沒有達到結束

function isInside(list,node) { 
    while(node !== undefined) { 
     for(var i = 0; i < list.length; i++) 
      if(node.className.indexOf(list[i]) > -1) 
       return true; 
     node = node.parentNode; 
    } 
    alert(1); // The code does not reach this when false 
    return false; 
} 

任何想法這裏有什麼問題嗎?

+0

變化'節點== undefined'到'節點== null'因爲'null'將是那裏是沒有'.parentNode'的結果!你也可以使用'!= null',它會測試'undefined'和'null',但它不應該是必須的。 – 2013-02-25 23:12:45

+0

將'node!== undefined'更改爲'node!= null'不起作用..其他想法? – user1163278 2013-02-25 23:18:01

+0

[Works for me](http://jsfiddle.net/qxAt4/) – 2013-02-25 23:31:05

回答

1

遵循此模式:

var current = node; 
while (current.parentNode){ 
// do stuff with node 
current = current.parentNode 

} 
+0

這樣做。謝謝您的幫助.. – user1163278 2013-02-25 23:19:39