Jquery中最喜欢和不喜欢的按钮不起作用

时间:2013-05-01 06:58:33

标签: javascript jquery

我需要开发一个按钮,帮助用户喜欢或不喜欢的文章。当用户点击按钮时,按钮或背景的颜色需要更改为橙色,当他取消收藏文章时,按钮上的颜色应该消失。

这是我目前在Jquery中的实现,但它只能运行一次。第二次不处理绑定。

我想我必须在第二次创建元素时再次处理绑定,但我不确定在哪里处理它。

    $('.colorStar').bind('click', function() {

            var id = $(this).parent().parent().parent().parent().attr('id');
            var removeElement = $(this).parent();
             $(removeElement).empty();
             $("<button data-action='show-contribute-how-to' class='btn colorStarred show'><i class='icon-star'></i></button>")
             .click(function (){
                var id = $(this).parent().parent().parent().parent().attr('id');
                var removeElement = $(this).parent();
                $(removeElement).empty();
                $(removeElement).append("<button data-action='show-contribute-how-to' class='btn colorStar show'><i class='icon-star'></i></button>");  
             }).appendTo(removeElement);

            $.ajax({
                type : "POST",
                url : "starNote",
                data : {
                    id : id
                }
            });
        });

HTML

<a class="star"><button class="btn colorStar hide" data-action="show-contribute-how-to"><i class="icon-star"></i></button></a>

http://jsfiddle.net/SLq8W/

1 个答案:

答案 0 :(得分:1)

委派活动:

$('body').on('click', '.colorStar', function() {

而不是

$('.colorStar').bind('click', function() {