2011-02-08 194 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); 
});