当JavaScript函数移动到外部.js文件时,它将停止工作

时间:2011-04-09 23:51:43

标签: javascript html include alert script-tag

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

“包含文件”警报有效,但“函数工作”则没有。我做错了什么?

2 个答案:

答案 0 :(得分:3)

确保在执行该功能之前包含该文件。

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

答案 1 :(得分:1)

你应该按照以下方式调用你的函数:

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

有关 window.onload 事件的详情,请参阅this

Code example on jsFiddle

相关问题