点击时,我有一个类add-to-favorite
的按钮,类更改为remove-from-favorite
,并且文件被添加到收藏夹中。当用户再次单击该按钮时,它已remove-from-favorite
该类已更改为add-to-favorite
,并且必须从收藏夹中删除该文件,但情况并非如此。即使班级为remove-from-favorite
,该按钮也会像add-to-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 :(得分:0)
只需对点击事件使用$(document).on():
$(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');
});