问题
I'm working on a function where users can click a star and a counter will increase and the word Unlike will appear. Then, if users click on Unlike the counter decreases and the word Unlike disappears. So far, it works.
The challenge is this: I want each user to only be able to click once (that's working now) but I want them to be able to click the star again IF they have already clicked the Unlike phrase (which would have removed the number from the counter). (Code and jsfiddle below).
HTML
<span href="" class="star">Star</span> <span class="star_number"></span>
· <span class="unstar">Unlike</span>
jQuery
$(function(){
$('.unstar').hide();
var count1=0;
$('.star').one("click", function() {
count1++;
$('.unstar').show();
$('.star_number').html(count1);
});
$('.unstar').one("click", function() {
count1--;
$('.unstar').hide();
$('.star_number').html(count1);
});
});
Also, here's the js fiddle - http://jsfiddle.net/j5qAs/
回答1:
Just change one
to bind
and add a check for :visible
or :hidden
$(function(){
$('.unstar').hide();
var count1=0;
$('.star').bind("click", function() {
if ($('.unstar').is(':hidden')) {
count1++;
$('.unstar').show();
$('.star_number').html(count1);
}
});
$('.unstar').bind("click", function() {
count1--;
$('.unstar').hide();
$('.star_number').html(count1);
});
});
http://jsfiddle.net/j5qAs/3/
回答2:
I think below should do the trick, If I understood your question correctly,
I used :visible
instead of count
because I assumed that the count will be returned from server and it may not be 1 or 0.. it will be > 1.
DEMO here
$(function(){
$('.unstar').hide();
var count1=0;
$('.star').bind("click", function() { // <-- changed to bind
if ($('.unstar').is(':visible')) return; // <-- added
count1++;
$('.unstar').show();
$('.star_number').html(count1);
});
$('.unstar').bind("click", function() { // <-- changed to bind
count1--;
$('.unstar').hide();
$('.star_number').html(count1);
});
});
回答3:
OK, so just reverse your logic. Whenever you hide .star, you need to show .unstar, and whenever you hide .unstar, you need to show .star.
来源:https://stackoverflow.com/questions/9163201/jquery-counter-uncounter-function