2014-12-12 7 views
0

script이 작동하지 않는 이유를 모르겠다. div 클래스를 변경하고 클래스 이름으로 elem에 바인드 된 이벤트를 수신하려고합니다.업데이트 된 클래스가있는 요소에 이벤트 수신기를 추가하는 방법은 무엇입니까?

$('.glyphicon-minus').on('click', function() { 
    var item = $(this).closest('.item'); 
    var child = $(item).children('.item-content'); 
    $(child).hide(); 
    $(this).removeClass('glyphicon glyphicon-minus').addClass('glyphicon glyphicon-plus'); 
}); 


$('.glyphicon-plus').on('click', function() { 
    var item = $(this).closest('.item'); 
    var child = $(item).children('.item-content'); 
    debugger; 
    $(child).show(); 
    $(this).removeClass('glyphicon glyphicon-plus').addClass('glyphicon glyphicon-minus'); 
}); 

답변

2

새 클래스 추가가 고려되지 않도록 바인딩이 이미 설정되었습니다. 당신은 당신의 바인딩까지 추상적으로 DOM 트리를 필요로하고 동적 노드에 그들을 위임 :

변경 $('.glyphicon-plus').on('click',

당신은 몇 년 전에 사람들이 이것을 달성하기 위해 $('.my-div').live('click'을 사용 불러올 경우

$('.some-permanent-container-div').on('click', '.glyphicon-plus',에 있지만, 모든 그것은 document에 바인딩을 첨부하고 위임했습니다. 가장 가까운 정적 컨테이너에 바인드하고 가능한 한 적은 수의 자식 티어만큼 위임하는 것이 훨씬 더 효율적입니다.

+0

아,'$ ('glyphicon-plus') 대신에 쓸 때 'click', function() {...})'이 줄'$ (document) .on ('click' , .glyphicon-plus ', function() {...})'모두 잘 동작합니다. – barbara

관련 문제