简体   繁体   中英

JavaScript - Count how many time a button is pressed(function)

I'm trying to count how many times a button is pressed, however I dont think this is right, because the count button keeps incrementing even if the 'Saying Hello' button isn't clicked

Any thoughts?

<!DOCTYPE html>

<html>
    <head>
        <title>JSExample</title>
    </head>

    <body>

        <script type="text/javascript">
            function hello() {
               alert("Hello there!");
            }

            var countClicks = 0;

            function upCount() { 

                if(document.getElementById('hello').onclick = "hello()") {
                    countClicks++;
                    alert(countClicks);
                    return true;
                } else {
                    return false;
                }

            }

        </script>

        <p><input type="button" name="button" value="Saying Hello" id="hello" onclick="hello();"/></p>

        <p><input type="button" name="click" value="Counting" id="click" onclick="upCount();"/></p>

    </body>

</html>

Y, i don't exactly understand your problem. Right now on click 'Saying hello' you are calling a function 'hello()' which only pops up an alert with 'Hello there'. On clicking 'Counting' button, you are checking a very strange condition that i don't exactly understand and then increment the value. So, if you want to count how many times 'say hello' was clicked, and then present it with 'Counting' button, use this code.

<!DOCTYPE html>

  <html> <head> <title>JSExample</title> </head> <body> <script type="text/javascript"> function hello() { alert("Hello there!"); countClicks++; } var countClicks = 0; function upCount() { alert(countClicks); } </script> <p><input type="button" name="button" value="Saying Hello" id="hello" onclick="hello();"/></p> <p><input type="button" name="click" value="Counting" id="click" onclick="upCount();"/></p> </body> </html> 

If this is not what you meant, please let me know :)

The condition if(document.getElementById('hello').onclick = "hello()") { is not correct. I'm not sure what it should be doing, but know what it does: it assigns a string hello() to the .onclick callback of the hello element. As a String can't be executed (as opposed to a Function ), it effectively removes the callback. You probably want something like this

 var countClicks = 0; function hello() { alert("Hello there!"); countClicks++; } function upCount() { alert(countClicks); } 
 <p><input type="button" name="button" value="Saying Hello" id="hello" onclick="hello();"/></p> <p><input type="button" name="click" value="Counting" id="click" onclick="upCount();"/></p> 

if(document.getElementById('hello').onclick == "hello()")

你错过了一个=

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM