简体   繁体   中英

HTML Javascript buttons not responding while clicking

Whenever I click the increment button , it doesn't show any output on the VS code terminal block.

It just shows the following output "if ($?) { start Firefox pEOPLEcOUNTERapp.htm }" just start the Firefox browser and when I click on increment button then --> no output

HTML CODE

<!DOCTYPE html>
<html lang="en">
    <head>
        <link rel = "stylesheet" href = "pEOPLEcOUNTERapp.css">
       
    </head>
    <body>
        <h1> People Entered</h1>
        <h2 id="count-el">0</h2>
        <script src="pEOPLEcOUNTERapp.js">
            // can write javascript
           
        
        </script>

        <button id="increment-btn" onclick="increment()">increment</button>
       
        
    </body>


</html>

    function increment(){ //javascript code
    console.log("THE BUTTON WAS clicked")
}

JavaScript Code:

function increment()
    console.log("THE BUTTON WAS clicked")
}

Try it like this:

 <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Document</title> <script> function increment() { console.log("THE BUTTON WAS clicked"); } </script> </head> <body> <button id="increment-btn" onclick="increment()">increment</button> </body> </html>

You have to add the script at the end of the document.

This should work (no separate js file)

<!DOCTYPE html>
<html lang="en">
    <head>
        <link rel = "stylesheet" href = "pEOPLEcOUNTERapp.css">
    </head>
    <body>
        <h1> People Entered</h1>
        <h2 id="count-el">0</h2>
        <script>
            function increment(){ 
                console.log("THE BUTTON WAS clicked")
            }
        </script>

        <button id="increment-btn" onclick="increment()">increment</button>
       
    </body>
</html>

It sounds like you want to update the count in that count-el element. If that's the case you do need to either defer the script or add your script call to just before the </body> tag to ensure the DOM has loaded, and your script can work on those elements.

This example removes the need for inline JS. It caches the elements, and then adds a listener to the button element. When that's clicked it calls the increment function which updates the text content of the count-el element.

 const count = document.querySelector('#count-el'); const btn = document.querySelector('#increment-btn'); btn.addEventListener('click', increment, false); function increment() { count.textContent = Number(count.textContent) + 1; }
 <h1> People Entered</h1> <h2 id="count-el">0</h2> <button id="increment-btn">increment</button>

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