Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
465 views
in Technique[技术] by (71.8m points)

html - Add event handler for body.onload by Javascript within <body> part

We want to include a maps from Google Maps API in our document. The documentation tells to initialize the map with a function called by the onload() event of the body.

The ordinary way to call:

<body onload="initialize_map();">

This doesn't work out for us because we're using Template::Toolkit and the <body> tag is already included in our wrapper. In short: The <body> tag is already printed when our Javascript code starts running.

I tried something like this but it does only work for onclick, not onload. I guess that's because the Javascript code is beneath the <body> tag itself.

var body = document.getElementsByTagName("body")[0];

body.addEventListener("load", init(), false);

function init() {
        alert("it works!");
};

Any help how to fire up a Google Maps map appreciated!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
body.addEventListener("load", init(), false);

That init() is saying run this function now and assign whatever it returns to the load event.

What you want is to assign the reference to the function, not the result. So you need to drop the ().

body.addEventListener("load", init, false);

Also you should be using window.onload and not body.onload

addEventListener is supported in most browsers except IE 8.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...