2013-08-02 77 views
-1

我對ul下的每個li元素綁定(或至少試圖)一個函數。onclick事件不在for循環中觸發

但事件永遠不會發生。看看下面的代碼,提示「富」 顯示,但下一個說「酒吧」應該顯示一旦點擊 在li標籤被調用。

function set_search_value() 
{ 
    var e = document.getElementById("res_ls"); 

    alert("foo"); 
    for (var i = 0; i < e.children.length; i++) 
    { 
     e.children[i].onclick = function() { 
      alert("bar"); 
     } 
    } 
} 

HTML

<ul id="res_ls" class="visible"> 
<li><span><span class="highlighted">test</span>ing.com</span> <span>(181)</span></li> 
</ul> 
+1

你''

0

只看該的jsfiddle這個例子: http://jsfiddle.net/drfisher/Ts7wZ/

var children = document.getElementById("res_ls").children; 
var child; 

for (var i = 0, len = children.length; i < len; i++) { 
    child = children[i]; 
    if (child.nodeType == 1) { 
     child.onclick = function() { 
      alert(this.textContent); 
     } 
    } 
}