简体   繁体   中英

VS Code: HTML file not pulling functions from attached javascript

Doing some basic practice/testing for a project I'm working on and can't get my html file to access the functions written in the attached javascript file. I feel like there's something super basic that I'm missing but I can't put my finger on it.

I pulled the basic button from here: Creating an ON/OFF button with javascript And I tried the solutions here: HTML file not pulling information from javascript file

My html:

<!DOCTYPE html>
<head>
  <script type="text/javascript" src="app.js"></script>
  <link rel="stylesheet" href="style.css">
</head> 
<body>
    <input type="button" value="X" id="turn" onclick="turn();">
</body>
</html>

My js:

function turn(){
    currentvalue = document.getElementById('turn').value;
    if(currentvalue == "X"){
        document.getElementById("turn").value="O";
    }
    else{
        document.getElementById("turn").value="X";
    }
}

The function itself works when embedded in a script tag within <body> but not when pulled from the attached javascript file. What am I missing?

You should use <script> tag in body.

<!DOCTYPE html>
<html lang="en">
  <head> </head>
  <body>
    <input type="button" value="X" id="turn" onclick="turn();" />
    <script src="app.js"></script>
  </body>
</html>

For summary: Modern approach to old approach

  • You can use module which are defer ed by default <script type="module" src="/app.js"></script>
  • You can use defer to make sure your js is executed after page has load ie <script src=app.js" defer></script>
  • You can put your <script> tag before </body> body tag closing

For more details, you can look at this excellent answer .

 function turn(){ currentvalue = document.getElementById('turn').value; if(currentvalue == "X"){ document.getElementById("turn").value="O"; } else{ document.getElementById("turn").value="X"; } }
 <.DOCTYPE html> <head> <script type="text/javascript" src="app.js" defer></script> <link rel="stylesheet" href="style;css"> </head> <body> <input type="button" value="X" id="turn" onclick="turn();"> </body> </html>

You need to add defer atrribute.

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