简体   繁体   中英

Javascript function not found in node.js server

I followed this to set up the node.js server: Using node.js as a simple web server

So I installed the serve-static npm.

I then created a file called file called test.html with the following code

<html>
<head>
  <h2>Google</h2>
</head>
<body>
  <button onclick="test()">Click me</button>
</body>
</html>

<script src="http://code.jquery.com/jquery-3.3.1.min.js" type="text/javascript">

  function test() {
    console.log('test');
  }

</script>

When I click on the button, I get:

Uncaught ReferenceError: test is not defined
at HTMLButtonElement.onclick (test.html:8)

and nothing else. This code looks ok...? Why is this function not found?

Remove your src part if you want to have your own function in between your script tags.

<script src="http://code.jquery.com/jquery-3.3.1.min.js"></script>
<script>
  function test() {
    console.log('test');
  }
</script>

Also, you should put your scripts before your </body>

Put your javascript just before closing body tag ( </body> )

And in your case you are binding event handler in the html itself, in this case you have to define those functions before you use them.

In this case put test() function code in head tag. It will work fine

Your JavaScript (script tag) is outside of html element. Put it in head or body.

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