更改类名和更改事件响应

时间:2016-06-02 09:48:03

标签: javascript jquery html javascript-events event-handling

点击时,我有一个类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

的javascript代码
$(".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

的javascript
$(".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');
 })

1 个答案:

答案 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');
 });