2014-12-13 6 views
0

내가 래퍼 태그의 하위 요소의 숫자를 만드는거야을 온 클릭 받기 :자바 스크립트 - 자식 요소 innerHTML을가

// 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이 루프에서 호출 되었기 때문입니다.

질문 : 정확한 자식 요소를 클릭 할 때 어떻게 choose_prompt에 올바른 ID를 전달하는 방법?

저는 jquery가없는 작업에 대처할 것으로 예상됩니다. JS와의 두 번째 하루이므로 엄격하지 않아야합니다.

도움을 주시면 감사하겠습니다. 감사!

답변

0

JS에는 블록 범위가 없으므로 모든 identificator 바인딩은 실제로 마지막으로 업데이트 된 값입니다.

것은 고립 된 폐쇄 만들 함수 호출로 랩 :

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

참고 :

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

는 또한 forEach 방법을 사용을, 모든 반복은 자신의 범위가 두 번째 방법를 들어, found_elements은 dom api (querySelectorAll, getElementsByTagName 또는 다른 유사한 방법)에서 반환하지만 실제 배열은 아닙니다. 그런 다음 배열 메서드를 호출해야합니다.

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

감사합니다. 그걸로 꽤 많은 시간을 보내십시오. 그게 문제를 해결했다. – Elena