簡體   English   中英

在 node.js 服務器中找不到 Javascript 函數

[英]Javascript function not found in node.js server

我按照這個來設置 node.js 服務器: Using node.js as a simple web server

所以我安裝了serve-static npm。

然后我使用以下代碼創建了一個名為 test.html 的文件

<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>

當我點擊按鈕時,我得到:

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

沒有別的。 這段代碼看起來還不錯...? 為什么找不到這個函數?

如果您想在script標記之間使用自己的函數,請刪除您的src部分。

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

另外,你應該把你的腳本放在你的</body>

將您的 javascript 放在關閉 body 標記之前( </body>

在您的情況下,您在 html 本身中綁定事件處理程序,在這種情況下,您必須在使用它們之前定義這些函數。

在這種情況下,將test()函數代碼放在 head 標簽中。 它會正常工作

您的 JavaScript(腳本標簽)在 html 元素之外。 把它放在頭上或身體里。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM