How to add 1 to a javascript variable by clicking a button?

后端 未结 3 2027
孤独总比滥情好
孤独总比滥情好 2021-01-29 06:14

I have very little experience with writing javascript and I need help desperately. I need to make so that when a button is clicked the score goes up by one similar to how the co

相关标签:
3条回答
  • 2021-01-29 06:30

    Your code already works. Here's a demo that demonstrates your code in action.

    I have added a function to display the click count:

    function updateClickCount() {
        document.getElementById("clickCount").innerHTML = clicks;
    }
    
    0 讨论(0)
  • 2021-01-29 06:36

    It'd be best code-organization-wise to define this function separately:

    var incrementCount = function(){
        clicks++;
    }
    

    And then to call that from your onclick:

    <button type="button" onClick ="incrementCount();" id="push"> NO.</button>
    

    And even better, it'd be smart to get rid of all of your inline javascript (AKA "obtrusive" javascript) alltogether, and make an object that will respond to all click events on all of these types of buttons automatically, but that may be above your level at the moment.

    You can add this to an external JS file that you include, and make a new "counter" object that automatically fires when the user clicks your button object.

    0 讨论(0)
  • 2021-01-29 06:45

    You can do it inline, but in the long run it is more maintainable to put the function inside your script, if you are going to reuse it later, or if you need to do other things as well when the button is clicked.

    JS

    function onClick(){clicks++;}
    

    HTML

    <button type="button" onClick ="onClick()" id="push"> NO.</button>
    
    0 讨论(0)
提交回复
热议问题