2012-04-29 5 views
2

저는 신입생 인 jQuery입니다. jQuery가 코드로 추가 된 요소를 조작 할 수 있다고 생각하지만, 지금은 그렇게 될 수 없다는 것을 알게되었습니다.jQuery에서 삽입 된 요소를 조작 할 수 있습니까?

$(function(){ 
    $("#addVideo").click(function(){ 
     $("#publisher").append("<div id='choseType'><input type='button' value='video'> <input value='music' type='button'> <input type='button' value='X'></div>"); 
    })  
    $("#choseType input:eq(0)").click(function(){ 
    $(this).addClass("selected"); 
    }) 
}) 

jquery의 제한 사항입니까, 아니면 내 코드의 오류입니까? 두 번째를 넣어 주면 첫 번째로 제대로 작동하지만, 한 번만 실행됩니다 (추가 된 #choseType을 제거하고 다시 추가하면 두 번째 클릭이 작동하지 않습니다). 그럼 어떻게 조작합니까? 코드 추가 요소? 감사!

답변

2
$(function(){ 
    $("#addVideo").click(function(){ 

     //create new content, and append to publisher 
     //also, reference the new content 
     var newContent = $("<div><input type='button' value='video'> <input value='music' type='button'> <input type='button' value='X'></div>").appendTo('#publisher'); 

     //then add a handler to input in the context of the new content 
     $("input:eq(0)", newContent).click(function(){ 
      $(this).addClass("selected"); 
     }); 
    })  
}) 
+0

고마워, 지금 작동합니다. 그리고 두 번째 클릭을 첫 번째 외부에 놓을 수없는 이유와 두 번째 클릭()이 추가 된 내용을 참조하지 않고 처음에 추가 될 때 한 번만 실행되는 이유는 무엇입니까? – LotusH

+0

@Wasabi 두 번째 핸들러가 실행될 때 이미 페이지에있는 요소에 클릭 핸들러 만 추가되었습니다. 새로운 요소에 핸들러를 추가하지 않았습니다. 새 요소를 추가하면 핸들러가 바인딩되지 않습니다. – Joseph

4

위임 동적이 아닌 요소에 이벤트 :

$(document).on('click', "#choseType input:eq(0)", function(){ 
    $(this).addClass("selected"); 
}); 

및 ID의 고유 있습니다!

+0

+1. on() 함수를 사용하려면 jQuery 1.7 이상이 있어야한다는 점에 유의하십시오. –

관련 문제