简体   繁体   English

javascript-window.onload无法正常工作

[英]javascript - window.onload not working

HTML: HTML:

<h1 id="id"></h1>
Hello!

JS: JS:

window.onload = function() {
    document.getElementById("id").innerHTML = "Hello world!";  
};

The above code is meant to set the innerHTML of the element with ID "id" to "Hello world!". 上面的代码旨在将ID为“ id”的元素的innerHTML设置为“ Hello world!”。 But it does not work. 但这行不通。

Fiddle . 小提琴

Why is this so? 为什么会这样呢?

Because you have told JSFiddle to assign the onload event handler when the onload event fires. 因为您已告知JSFiddle当onload事件触发时分配onload事件处理程序。

Since the event doesn't fire a second time, the function never runs. 由于该事件不会再次触发,因此该函数永远不会运行。

Change the "where to put the JS" option and it works . 更改“里把JS”选项, 它的工作原理

I guess according to your code the inner html will be replaced by "Hello World" and its working as it should be as shown below ..I guess some problem with your jsfiddle setting like select "No wrap - in <head>" in the second dropdown. 我猜根据您的代码,内部html将被“ Hello World”替换,其工作方式应如下所示。.我猜您的jsfiddle设置存在一些问题,例如,选择了"No wrap - in <head>"第二个下拉菜单。

window.onload = function() {
    document.getElementById("id").innerHTML = "Hello world!";  
};

Demo :- http://jsfiddle.net/Rqe6K/3/ 演示: -http : //jsfiddle.net/Rqe6K/3/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM