2016-06-02 2 views
0

버튼을 클릭하면 클래스가 remove-from-favorite으로 변경되고 파일이 즐겨 찾기에 추가됩니다. add-to-favorite 버튼이 있습니다. 사용자가 버튼을 다시 클릭하면 remove-from-favorite 클래스가 add-to-favorite으로 변경되고 파일을 즐겨 찾기에서 제거해야하지만 그렇지 않습니다. 클래스가 add-to-favorite; 인 경우에도 버튼은 remove-from-favorite처럼 작동합니다. 어떤 아이디어? 여기 클래스 이름 변경 및 이벤트 응답 변경

코드입니다 : 여기
<button type="button" class="add-to-favorite" name="button"><i class="material-icons">favorite_border</i></button> 

여기 add-to-favorite

$(".add-to-favorite").on("click", function(event) { 
var clicked_button = $(this); 
    clicked_button.html("<i class='material-icons'>close</i>"); 
    clicked_button.removeClass('add-to-favorite'); 
    clicked_button.addClass('remove-from-favorite'); 
}) 

의 자바 스크립트 코드 remove-from-favorite

$(".remove-from-favorite").on("click", function(event) { 
var clicked_button = $(this); 
    clicked_button.html("<i class='material-icons'>favorite_border</i>"); 
    clicked_button.removeClass('remove-from-favorite'); 
    clicked_button.addClass('add-to-favorite'); 
}) 

답변

0

에 대한 자바 스크립트는 그냥 $ (문서) CSTE 연구진를 사용하다 클릭 이벤트() :

$(document).on("click",".add-to-favorite", function(event) { 
    var clicked_button = $(this); 
     clicked_button.html("<i class='material-icons'>close</i>"); 
     clicked_button.removeClass('add-to-favorite'); 
     clicked_button.addClass('remove-from-favorite'); 
}); 

$(document).on("click",".remove-from-favorite", function(event) { 
    var clicked_button = $(this); 
     clicked_button.html("<i class='material-icons'>favorite_border</i>"); 
     clicked_button.removeClass('remove-from-favorite'); 
     clicked_button.addClass('add-to-favorite'); 
}); 
+0

감사합니다. 문제가 해결되었습니다. 제발 $ (문서)가 왜 효과가 있었고 다른 방법은 그렇지 않은지 말해 주시겠습니까? –

+0

동적으로 추가/업데이트 된 요소의 경우 document.on() 만 사용해야하기 때문에 –