2016-06-02 9 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> 

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

ちょうど$(文書).onを使用するためにここで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'); 
}) 

ためのJavaScriptコードではJavaScriptですクリックイベントの件数():

$(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()のみを使用する必要があるため –

関連する問題