I was experimenting with javascript the other day, and wanted to see whether a certain function would work. So I did my HTML:

<body>
    <p id="paragraph"></p>
</body>

(of course, in the actual document I have set my doctype and created html tags and so forth)

And then wrote my javascript (which was linked to in the head correctly):

(function(){
    document.getElementById("paragraph").innerText = "Hi there!";
}());

Now, I opened my html and was a bit confused as to why my <p> did not contain any text, so I thought maybe the IIFE wasn't running on page load, so I tried something else:

(function(){
    console.log("Hi there!");
}());

Opened it again, and saw that the javascript had run fine that time; the console had printed 'Hi There' just as normal. I was a bit confused now, so then I tried:

window.onload = function(){
    document.getElementById("paragraph").innerText = "Hi there!";
}

And it all worked perfectly! The paragraph contained 'Hi there' just like it should have (well, I think so) the first time!

Can anyone account for this absurd behavior? Why isn't (function(){/*stuff*/}()); working for the .innerText?

有帮助吗?

解决方案

The way browsers work in most cases, is they process the html file first (including executing any scripts in it, in order), then create DOM elements such as your paragraph.

So when your IIFE was executed, the paragraph didn't exist yet (surely this must have printed something to your console too).

console.log is a different thing - the console object exists before the html is even loaded, which is why that worked fine.

Also, you want a lower-case d in getElementById

其他提示

The load event fires at the end of the document loading process. At this point, all of the objects in the document are in the DOM, and all the images and sub-frames have finished loading.

MDN - window onload

if you do something like this it will work:

// wait for the dom to be ready...
window.onload = function(){
    // update the element...
    (function(){
        document.getElementById("paragraph").innerText = "Hi there!";
    }());    
}
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top