简体   繁体   中英

How to increase and decrease a counter from one button - click and click again jQuery

This is the code that I am currently using:

<script>
   $(".lk").click(function(){
   $(this).find("#lke").html(function(i, val) { return val*1+1 });
   });

   $(".lk").click(function(){
   $(this).find("#lke").html(function(i, val) { return val*1-1 });
   });
</script>

When the user clicks on the button, the value of #lke increases by 1. When he clicks again, the value decreases by 1. The code that I am currently using does not work so how would I fix this?

Your code doesn't work because you assign two events for every click - one which increases the value and one which decreases it, so nothing happens.

You could use an external variable such as toAdd to determine which action to do:

var toAdd = 1;
$(".lk").click(function(){
    newValue = oldValue + toAdd;
    toAdd *= -1;
    ...
});

You can use an external var to decide if you have to increment o decrement the value

<script>
   var increment = true;
   $(".lk").click(function(){
      var lke = $(this).find("#lke"), 
          value = parseInt(lke.html()) || 0;

      lke.html( increment ? value + 1 : value - 1);
      increment = !increment;
   });
</script>

Try something like this:

$(".lk").click(function() {
   if ($(this).hasClass('clicked')) {
       $(this).removeClass('clicked'));
       $(this).find("#lke").html(function(i, val) { return val*1-1 });
   } else {
       $(this).addClass('clicked');
       $(this).find("#lke").html(function(i, val) { return val*1+1 });  
   }
});

You could also use a data attribute instead of checking for a class aswell.

Or use toggleClass() .

$(".lk").click(function() {
   if ($(this).hasClass('clicked')) {
       $(this).toggleClass('clicked'));
       $(this).find("#lke").html(function(i, val) { return val*1-1 });
   } else {
       $(this).toggleClass('clicked');
       $(this).find("#lke").html(function(i, val) { return val*1+1 });  
   }
});

You put two call of the same object, try this instead

<script>
   var val = 0; // Put the original value
   var negative = false;
   $( document ).ready(function() { // You need to declare document ready
      $(".lk").click(function(){
         val = val + ((negative) ? -1 : 1); // Change if its positive or negative
         negative = (negative) ? false : true;
         $("#lke").text(val); // Adjust the html ?
      });
   });
</script>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM