【问题标题】:JavaScript function stops working when it is moved to an external .js fileJavaScript 函数在移动到外部 .js 文件时停止工作
【发布时间】:2011-04-09 23:51:42
【问题描述】:

我将一个函数从一个 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>

“包含文件”警报有效,但“功能有效”无效。我做错了什么?

【问题讨论】:

    标签: javascript html include alert script-tag


    【解决方案1】:

    确保在执行函数之前包含该文件。

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

    【讨论】:

      【解决方案2】:

      你应该通过以下方式调用你的函数:

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

      有关 window.onload 事件的更多信息,请参阅this

      Code example on jsFiddle

      【讨论】:

      • 有没有办法像 C# 中的 += 一样订阅多个函数来触发 onload?
      • @smartcaveman 这很容易做到,你只需要将它们列出到匿名函数中: window.onload = function() { func1();函数2();函数3(); ... funcn(); };
      • 如果你想在不同的时间注册他们怎么办?
      • @smartcaveman,“注册”是什么意思?您的函数将从您定义的匿名函数中按顺序 (func_1, func_2, func_3...func_n) 被调用(参见jsfiddle.net/proudlygeek/s794p
      • 当代码依赖于 DOM 时,您应该(通常)只将执行推迟到窗口上的加载或就绪事件。否则,如果您正在使用加载,它可能会破坏用户的浏览体验,因为在加载每个资源之前,代码不会被执行。
      猜你喜欢
      • 2022-07-08
      • 2019-11-09
      • 2012-08-01
      • 1970-01-01
      • 2016-02-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-08-08
      相关资源
      最近更新 更多