【问题标题】:How do you automatically run an external JavaScript function with a variable? [duplicate]如何使用变量自动运行外部 JavaScript 函数? [复制]
【发布时间】:2017-12-02 13:46:17
【问题描述】:

我正在尝试在页面加载时运行外部 javascript 函数,并且该函数采用一个变量,我只能通过调用 javascript 函数的页面。

HTML 页面

<head>
<script src="path/to/file.js" type="text/javscript>
window.onload = function() {
doFunction(variable);
}
</script>
</head>

Javascript 文件

function doFunction(variable){
//do the stuff here
}

【问题讨论】:

  • 每个&lt;script&gt; 元素可以有一个src 或内联代码,不能两者合二为一。将内联代码移动到第二个 &lt;script&gt; 元素。 – Inline Script with SRC Attribute?
  • @JonathanLonowski 我会做一个 window.onload(doFunction(variable)); 吗?如果我使用 src
  • @JonathanLonowski 怎么样?
  • 在当前&lt;/script&gt; 之后添加第二个&lt;script&gt; 元素。将内联 JavaScript 移入其中。
  • @JonathanLonowski 你解决了!

标签: javascript jquery html


【解决方案1】:
<head>
<script src="path/to/file.js" type="text/javscript></script>
<script>
$(window).load(function() {
      doFunction(variable);
});
</script>
</head>

引用脚本标签(用于包含外部文件)不应包含任何外部 JavaScript 代码。您只能引用外部文件。

添加应该在单独脚本标签之间的任何其他 javascript

【讨论】:

    【解决方案2】:

    由于您没有异步加载file.js,因此您可以将脚本包含在标头中。只要在脚本加载后调用该函数,它就可以正常工作。

    <html>
    <head>
        <script src="path/to/file.js" type="text/javscript>
    </head>
    <body>
    <script type="text/javascript">
        window.onload = function() {
            doFunction('someVal');
        };
    </script>
    </body>
    </html>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-08-05
      • 2017-06-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-08-02
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多