2014-04-26 7 views
1

div가 있습니다. 이 div에는 div를 비우고 새로운 내용으로 채우는 버튼이 있습니다.jQuery : 클릭 이벤트 내에서 클릭 이벤트

div가 새로운 콘텐츠로 채워질 때이 div를 채운 요소 중 하나에서 click() 함수를 호출 할 수없는 문제가 있습니다. 내가 도대체 ​​뭘 잘못하고있는 겁니까?

맨 아래까지 코드 블록이 문제가됩니다.

$(document).ready(function(){ 
     function newGame(){ 
      //Empty the game window of contents. 
      $('#previewWindow').empty(); 

      //Add the following HTML to the game window. 
      $('#previewWindow').append("<div id='spriteBox' align='center'><img id='sprite1' src='images/sprites/172(noSelect).png' border='0'/><img id='sprite2' src='images/sprites/88(noSelect).png' border='0' /><img id='sprite3' src='images/sprites/196(noSelect).png' border='0' /><div id='info' align='center'>TEST</div></div>"); 

      //Hover effects for Sid's character. 
      $('#sprite1').hover(function(){$(this).attr('src', 'images/sprites/172.png');$('#crumbling').get(0).play();},function(){$(this).attr('src','images/sprites/172(noSelect).png');} 
      ); 

      //Hover effects for Grim's character. 
      $('#sprite2').hover(function(){$(this).attr('src', 'images/sprites/88.png');$('#crumbling').get(0).play();},function(){$(this).attr('src', 'images/sprites/88(noSelect).png');} 
      ); 

      //Hover effects for Falas's character. 
      $('#sprite3').hover(function(){$(this).attr('src', 'images/sprites/196.png');$('#crumbling').get(0).play();},function(){$(this).attr('src','images/sprites/196(noSelect).png');} 
      ); 
     }; 

     //Execute the following code block if New Game is clicked. 
     $('#newGame').click(function(){ 
      newGame(); 
     }); 

     //Execute the following code block if Sid is clicked. 
     $('#sprite1').click(function(){ 
      alert('Hello'); 
     }); 
    }); 
+0

는 소리하는 것입니다. ID는 문서 컨텍스트에서 고유해야 함을 잊지 마십시오. https://learn.jquery.com/events/event-delegation/ –

답변

1

div 핸들러를 div에있는 버튼에 직접 연결했기 때문에.

div 콘텐츠를 다시로드하면 클릭 핸들러가없는 새 버튼이 생깁니다.

이 시점에서 이벤트 위임을 사용하고 싶습니다. 즉, 처리기를 콘텐츠 div에 대신 연결하여 비울 때 손실되지 않도록 할 수 있습니다. 당신이 id="newGame"있는 모든 요소에 #previewWindow 내부를 클릭 할 때마다

$('#previewWindow').on('click','#newGame',function(){ 
     newGame(); 
    }); 

    //Execute the following code block if Sid is clicked. 
    $('#previewWindow').on('click','#sprite1',function(){ 
     alert('Hello'); 
    }); 

무엇을 기본적으로 의미하는 것은,이다, 그것은 새로운 게임을 호출

난 콘텐츠 사업부는 그래서 여기 "previewWindow" 당신이 이벤트 위임을 어떻게 가정 .

+0

감사합니다, 감사합니다, 천 번 감사합니다! 매우 빠른 응답과 도움이되는 모든 것. 내가 너를 모두 상향 조정할만큼 충분히 높은 담당자를 갖고 있었으면 좋겠다. 이 항목은 가장 명확하고 직접적이며 쉽게 따라 할 수 있습니다. 나는 그것이 나를 (4 분 정도 같이)하게 할 수있는 한 빨리 대답으로 선택할 것이다. – w0lf

0

뒤에을 추가하면 클릭 이벤트가 등록되며 클릭 이벤트는 등록한 이후의 데이터에는 적용되지 않습니다.

이 문제를 해결하려면 jQuery("#container").on(event, selector, handler(event)) 메서드를 사용하여 아직 추가되지 않은 요소에 이벤트를 등록 할 수 있습니다.

$('#previewWindow').on('click', '#sprite1', function(){ 
    alert('Hello'); 
}); 
0

놓습니다 newGame() 기능 내부의 $('#sprite1').click() 이벤트 :

$(document).ready(function(){ 
    function newGame(){ 
     //Empty the game window of contents. 
     $('#previewWindow').empty(); 

     //Add the following HTML to the game window. 
     $('#previewWindow').append("<div id='spriteBox' align='center'><img id='sprite1' src='images/sprites/172(noSelect).png' border='0'/><img id='sprite2' src='images/sprites/88(noSelect).png' border='0' /><img id='sprite3' src='images/sprites/196(noSelect).png' border='0' /><div id='info' align='center'>TEST</div></div>"); 

     //Execute the following code block if Sid is clicked. 
     $('#sprite1').click(function(){ 
      alert('Hello'); 
     }); 

     //Hover effects for Sid's character. 
     $('#sprite1').hover(function(){$(this).attr('src', 'images/sprites/172.png');$('#crumbling').get(0).play();},function(){$(this).attr('src','images/sprites/172(noSelect).png');} 
     ); 

     //Hover effects for Grim's character. 
     $('#sprite2').hover(function(){$(this).attr('src', 'images/sprites/88.png');$('#crumbling').get(0).play();},function(){$(this).attr('src', 'images/sprites/88(noSelect).png');} 
     ); 

     //Hover effects for Falas's character. 
     $('#sprite3').hover(function(){$(this).attr('src', 'images/sprites/196.png');$('#crumbling').get(0).play();},function(){$(this).attr('src','images/sprites/196(noSelect).png');} 
     ); 
    }; 

    //Execute the following code block if New Game is clicked. 
    $('#newGame').click(function(){ 
     newGame(); 
    }); 

}); 
+0

이것은 여전히 ​​작동 할 것이고,'.click()'이벤트 핸들러를 여러 번 호출 할 것이고, ['.on()'] (http://api.jquery.com)와는 반대로 최적이 아닙니다./on /) 메소드. –

0

또 다른 옵션은 이벤트를 위임 할 필요가 같은

$(document).ajaxComplete(function() { 
    $('#sprite1').on('click', function() { 
     alert('Hello'); 
    }); 
});