我需要开发一个按钮来帮助用户收藏或取消收藏文章。当用户点击按钮时,按钮或背景的颜色需要变为橙色,当他取消收藏文章时,按钮上的颜色应该消失。
这是我当前在 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>