2011-02-08 184 views
2
$('.fav').live('click', function(e){ 
    $(this).toggleClass('highlight'); 
    //increase the number by 1 

HTML:使用jquery将数字增加1?

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

如何使用jQuery来增加每次李之间的数它的点击?谢谢

回答

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

你想看看.html().text()。这里有一个例子:

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

+1,这是迄今为止最好的答案(由于使用`Number`而不是`parseInt`,'text()`而不是`html()`),但目前没有upvotes ? – 2011-02-08 05:35:28

+0

@ box9小心解释为什么`Number`比`parseInt`好? http://jsperf.com/number-vs-parseint-vs-plus/7为什么`text()`比`html()`更好? – 2011-02-08 06:07:27

1

只需使用一个插件。

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

然后调用

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

HTML:

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

的jQuery:

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

点击现有的按钮,这样,当你可以增加计数器:

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