简体   繁体   中英

Increasing a number by 1 using jquery?

$('.fav').live('click', function(e){
    $(this).toggleClass('highlight');
    //increase the number by 1

html:

<li class="fav light_gray_serif">5</li>

how can i use jquery to increase the number between the li everytime its clicked? thanks

var num = parseInt($.trim($(this).html()));
$(this).html(++num)

You want to take a look at .html() or .text() . Here is an example:

$(this).text(function(i, t) {
    return Number(t) + 1;
});

HTML:

<span id="counter">0</span>

jQuery:

$('#counter').text(Number($('#counter').text())+1);

You can increase the counter when clicking an existing button like this:

$(document).on('click','#your-button', function(){
  $('#counter').text(Number($('#counter').text())+1);
});

Just use a plugin.

(function($) {
    $.extend($.fn, {
         "addOne": function() {
              var num = parseInt(this.text(), 10);
              this.text(++num);
         },
         "subtractOne": function() {
              var num = parseInt(this.text(), 10);
              this.text(--num);
         }
    });
}(jQuery))

Then call

$(".fav").live("click", function(e) {
     $(this).toggleClass("highlight").addOne();
});

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