문제

문제의 태그가 서버에서 생성 될 때 (XMPHTTP 요청을 통해) AddEventListener (window.onload)를 사용하여 클릭 이벤트를 추가하려면 어떻게합니까?

감사!

도움이 되었습니까?

해결책

이벤트 Hanlders를 적용해야합니다 ~ 후에 요소는 DOM에 삽입되었습니다

다른 팁

DOM로드로 제공되는 부모 요소의 이벤트를 처리하려고 시도한 다음 이벤트와 관련된 요소를 얻을 수 있습니다.

<ul id="list">
  <li id="first">The first</li>
  <li id="second">The second</li>
  <li id="third">The third</li>
</ul>

document.getElementById('list').onclick(function(e){
  o = e.originalTarget;
  // if you click on second li o will bi the same as document.getElementById('first')
  // even if li with id "first" is inserted to DOM after creating this event handler to "list"
  // so here you can perform actions with it
  // hope it will help
});

감사합니다.

아래 코드를 XMLHTTP 요청의 "On Success"이벤트에 추가하여 DOM을 서버에서 나오는 요소와 함께 추가하여이를 해결했습니다. 그것은 나를 위해 일했다. 조쉬, 당신은 내 머리가 올바른 방향으로 움직였다 (코드 일러스트레이션을 보는 것이 좋았지 만) 그래서 나는 당신의 응답을 답으로 표시했습니다.

if ((xmlhttp.readyState == 4) && (xmlhttp.status == 200)) {

                        var m_sel=document.getElementById("fcat");

                        if (m_sel) {

                            var maxi = m_sel.options.length;

                            for( var i = 0; i < maxi; i++ )
                            {
                                var option = m_sel.options[i];
                                    option.addEventListener( "click", toggleElem, true );

                            }                                 

                        }        
}
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top