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

前端 未结 7 1356
轻奢々
轻奢々 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:32

    You cannot use ++ on something which is not a variable, this would be the closest you can get:

    $('#counter').html(function(i, val) { return +val+1 });
    

    jQuery's html() method can get and set the HTML value of an element. If passed a function it can update the HTML based upon the existing value. So in the context of your code:

    $("#update").click(function() {
        $('#counter').html(function(i, val) { return +val+1 });
    }
    

    DEMO: http://jsfiddle.net/marcuswhybrow/zRX2D/2/

    When it comes to synchronising your counter on the page, with the counter value in your database, never trust the client! You send either an increment or decrement signal to you server side script, rather than a continuous value such as 10, or 23.

    However you could send an AJAX request to the server when you change the HTML of your counter:

    $("#update").click(function() {
        $('#counter').html(function(i, val) {
            $.ajax({
                url: '/path/to/script/',
                type: 'POST',
                data: {increment: true},
                success: function() { alert('Request has returned') }
            });
            return +val+1;
        });
    }
    

提交回复
热议问题