2014-12-13 207 views
0

我創建的包裝標籤的數子元素:使用Javascript - 獲取子元素的innerHTML的onclick

// display prompts in html 
    function show_prompts(found_elements){ 
      var div = document.getElementById("prompts"); 

      // iterate through list of found words 
      for (var i=0; i < found_elements.length; i++){ 

      // initialize child element 
      var p = document.createElement('p'); 

      // creating specific ID for each child 
      identificator = 'variant'+[i]; 
      p.id = identificator; 

      // filling child with text 
      p.innerHTML = found_elements[i]; 

      p.addEventListener("click", function(){choose_prompt(identificator);}); 
      //p.setAttribute("onclick", "choose_prompt()"); 
      div.appendChild(p); 
      } 
    } 

目標: 那點擊瀏覽器中的子元素之一的功能後, choose_prompt激活並使用單擊元素的innerHTML進行一些工作。

問題: 當點擊,choose_prompt決定最後一次迭代ID爲所有的元素。我知道它是因爲在循環中調用了addEventListener

問: 如何確切的子元素,當點擊正確的ID傳遞給choose_prompt

我希望能夠應付沒有任何jQuery的任務。 我與JS的第二天,所以不要嚴格。

希望有任何幫助。謝謝!

回答

0

JS沒有塊範圍,因此所有identificator綁定實際上是最後更新的值。

用一個函數調用包裹它創建一個孤立封閉:

for (var i=0; i < found_elements.length; i++) { 
    (function(i) { 
    // do your job here with i 
    })(i) 
} 

或者使用forEach方法,每次迭代都有自己的適用範圍:

found_elements.forEach(function(element, i) { 
    // do your job here with i 
}); 

注:第二個方法,如果由dom api(querySelectorAllgetElementsByTagName或其他類似的方法)返回found_elements,它不是一個真正的數組。那麼你應該調用它的數組方法:

Array.prototype.forEach.call(found_elements, function(element, i) { 
    // do your job here with i 
}); 
+0

非常感謝!花足夠多的時間吧,呵呵。這解決了問題 – Elena 2014-12-13 16:13:08