简体   繁体   中英

Javascript not working Visual Studio

My current code is:

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <title>App1</title>
    <link href="css/default.css" rel="stylesheet" />
</head>
<body>
    <p id="test">Content goes here!</p>
    <button onclick="myFunction()">Try it</button>
    <script>  
        function myFunction() {
            document.getElementById("test").innerHTML = "Working";
        }
    </script>
</body>
</html>

When I debug on Visual Studio 2017 the html works fine. Picture of code execution

However, clicking the button does nothing. No error messages, just nothing happens. If I copy and paste the code into a text document, format it as an html and test that in Chrome, everything works fine. Any idea why this happens?

Edit: It was made as a Blank JavaScript App if that changes anything

I can't say why that would be the case. There is nothing in your code that would indicate an issue, other than it is possible that the file open in your browser is NOT the file you are editing in Visual Studio.

Make sure that, from Visual Studio, you right click on the source code and choose to run the page in a browser.

I can say that you should not be using inline HTML event attributes ( onclick , etc.), here's why.

Try reformatting your code to use modern, standards-based code like this:

 <!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title>App1</title> <link href="css/default.css" rel="stylesheet" /> </head> <body> <p id="test">Content goes here!</p> <button id="btn">Try it</button> <script> // Get DOM references var p = document.getElementById("test"); var btn = document.getElementById("btn"); btn.addEventListener("click", myFunction); function myFunction() { p.innerHTML = "Working"; } </script> </body> </html> 

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