簡體   English   中英

將JavaScript函數移至外部.js文件時,該函數停止工作

[英]JavaScript function stops working when it is moved to an external .js file

我將功能從html頁面移到了包含的參考文件中。 它停止工作了。

該文件的完整內容是:

alert('file included');

function doAlert() {
   alert('functions work');
}

在html頁面中,我有

<html>
<head><title>Page</title></head>
<body>
  HTML Template Header

  Some Content 

  ASP.NET MVC Partial View Starts
  <script type="text/javascript">
      doAlert();
  </script>
  ASP.NET MVC Partial View ends

  HTML Template Footer

  <script type="text/javascript" src="/Scripts/wtf.js"></script>
</body>
</html>

“包含文件”警報有效,但“功能正常”無效。 我究竟做錯了什么?

在執行功能之前,請確保包含文件。

<script src="file.js" type="text/javascript"></script>
<script type="text/javascript">
   doAlert();
</script>

您應該通過以下方式調用函數:

window.onload = function() {
    doAlert();
    // func_1();
    // func_2();
    // func_3();
    // ...
    // func_n();
};

請參見關於window.onload事件的更多信息。

jsFiddle上的代碼示例

暫無
暫無

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

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