javascript 如何在window.load 上调用外部javascript?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7037256/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 22:46:43  来源:igfitidea点击:

How to call external javascript on window.load?

javascripthtml

提问by Wan

I want to put this in my website

我想把这个放在我的网站上

<script type="text/javascript"> <!-- window.onload = hello; function
hello() { var name = prompt("What is your name", "") alert ( "Hello "
+ name + "! Welcome to my forum.") } </script>

but I dont want to put it in index but in separate file, let say hello.js

但我不想把它放在索引中,而是放在单独的文件中,比如说 hello.js

How can I call it from index file so when I click the index.html, it will immediately prompt for my name. (for example)

如何从索引文件中调用它,以便当我单击 index.html 时,它会立即提示输入我的名字。(例如)

I put <script src="hello.js"></script>does not work.

我把<script src="hello.js"></script>不起作用。

回答by Andrius Virbi?ianskas

Your hello.js should look something like this:

你的 hello.js 应该是这样的:

window.onload = hello; 

function hello() { 
    var name = prompt("What is your name", "");
    alert("Hello " + name + "! Welcome to my forum."); 
}

and then the <script src="hello.js"></script>should work just fine.

然后<script src="hello.js"></script>应该可以正常工作。

回答by Peter Perhá?

There shouldn't be much more to it than importing that script. But then, your script is all broken. Of course it won't work, unless your browser can interpret it. Take a look at javascript basics. On the first look, you don't seem to be using semicolons to delimit individual statements. Also, you have opened an HTML comment <!--but you have never closed it...

应该没有比导入该脚本更多的内容了。但是,你的脚本全都坏了。当然它不会工作,除非您的浏览器可以解释它。看看javascript基础知识。乍一看,您似乎没有使用分号来分隔各个语句。此外,您打开了一个 HTML 注释,<!--但您从未关闭它...

回答by Ankit

Change your code to something like this:

将您的代码更改为如下所示:

<script type="text/javascript"> 
var name = prompt("What is your name", "");
alert ( "Hello " + name + "! Welcome to my forum.");  </script>

i.e, remove any function and just write your alert directly, this should work.

即,删除任何功能并直接编写您的警报,这应该可以工作。

回答by pachomp

Ubuntu Server 16.04

Ubuntu 服务器 16.04

external JS

外部JS

change-from: --> window.onload = hello;

更改:--> window.onload = hello;

change-to: --> window.document.body.onload = hello;

更改为:--> window.document.body.onload = hello;

html

html

body onload="hello()"

身体加载=“你好()”