尽量不要在可能的情况下重复自己并避免不必要的元素:
HTML:
CSS:
a#fav{
background: url('../images/addFavorit.png');
display: block;
width: 48px;
height: 48px;
}
a#fav.active{
background: url('../images/addFavorit_hover.png');
}
JAVASCRIPT
function addFav(){
$.ajax({
url: "/favorites/add",data: {"id": articleID},success: function(){
$('a#fav')
.addClass('active')
.attr('title','[-] Remove from favorites')
.unbind('click')
.bind('click',removeFav)
;
}
});
}
function removeFav(){
$.ajax({
url: "/favorites/remove",success: function(){
$('a#fav')
.removeClass('active')
.attr('title','[+] Add as favorite')
.unbind('click')
.bind('click',addFav)
;
}
});
}
//this will make the link listen to function addFav (you might know this already)
$('a#fav').bind('click',addFav);
第一次调用addFav()中指定的url时单击链接,成功处理后将调用成功定义的函数.结果:
由于重新绑定,第二次单击将调用removeFav().结果将是:
在那之后,如果您的服务器没有采取行动,这将是一个无限循环.