jQuery:使用功能创建收藏夹按钮? [英] jQuery: Making a Favorite button with function?
问题描述
现在我做了这个:
<a href="#" title="[+] Add as favorite"><div class="addFavorite"></div></a>
class ="addFavorite",是正常的灰色星形.
the class="addFavorite", is a normal grey star.
然后我有另一个class ="AlreadyFavorite",它是黄色的星星.
Then i have another class="AlreadyFavorite", that is a yellow star.
我想创建一个函数,所以当您单击灰色星形时,它会发送一个ajax调用(?),然后成功后,它会变成黄色(将类更改为AlreadyFavorite).
I want to make a function, so when you click on the grey star, it sends an ajax call(?) and then on success it turns yellow(changing class to AlreadyFavorite).
我知道如何制作一个发送ajax调用的onclick函数,但是如何更改样式/将图像图标更改为黄色?
I know how to make a onclick function that send a ajax call, but how do i change the style/change the image icon to yellow?
CSS:
.addFavorit{
background: url('../images/addFavorit.png');
width: 48px;
height: 48px;
}
.alreadyFavorit{
background: url('../images/addFavorit_hover.png');
width: 48px;
height: 48px;
}
推荐答案
尽量不要重复自己,并避免使用不必要的元素:
Try not to repeat yourself where possible and avoid unneeded elements:
HTML:
<a href="#" id="fav" title="[+] Add as favorite"> </a>
CSS:
a#fav{
background: url('../images/addFavorit.png');
display: block;
width: 48px;
height: 48px;
}
a#fav.active{
background: url('../images/addFavorit_hover.png');
}
JAVASCRIPT
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",
data: {"id": articleID},
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时单击该链接,并在成功处理后调用成功定义的函数.结果:
Clicking the link the first time the url specified in addFav()
will be called and after successful processing the function defined in success will be called. The result:
<a href="#" id="fav" class="active" title="[-] Remove as favorite"> </a>
由于重新绑定,第二次单击将调用removeFav()
.结果将是:
The second click will call removeFav()
due to the rebinding. The result will be:
<a href="#" id="fav" class="" title="[+] Add as favorite"> </a>
在那之后,如果您的服务器无法正常工作,这将是一个无休止的循环.
After that it's an endless loop given your server doesn't act out.
这篇关于jQuery:使用功能创建收藏夹按钮?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!