开发者

How to call external javascript on window.load?

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

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

开发者_StackOverflow社区

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


Your hello.js should look something like this:

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.


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...


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.


Ubuntu Server 16.04

external JS

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

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

html

body onload="hello()"

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜