javascript 使用 jquery 将数字增加 1?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4929608/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 15:23:43  来源:igfitidea点击:

Increasing a number by 1 using jquery?

javascriptjquery

提问by getaway

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

html:

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

我如何使用 jquery 每次点击时增加 li 之间的数字?谢谢

回答by The Scrum Meister

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

回答by PleaseStand

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

你想看看.html().text()。下面是一个例子:

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

回答by diazdeteran

HTML:

HTML:

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

jQuery:

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);
});

回答by Raynos

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();
});