jQuery - Increase the value of a counter when a button is clicked

前端 未结 7 1363
轻奢々
轻奢々 2020-11-27 02:50

I\'m making a system where a user clicks a button and their score increases. There is a counter which I would like to increase the value of using jQuery (so that the page do

7条回答
  •  死守一世寂寞
    2020-11-27 03:25

    Several of the suggestions above use global variables. This is not a good solution for the problem. The count is specific to one element, and you can use jQuery's data function to bind an item of data to an element:

    $('#counter').data('count', 0);
    $('#update').click(function(){
        $('#counter').html(function(){
            var $this = $(this),
                count = $this.data('count') + 1;
    
            $this.data('count', count);
            return count;
        });
    });
    

    Note also that this uses the callback syntax of html to make the code more fluent and fast.

提交回复
热议问题