简体   繁体   中英

Whats the difference between calling function loadText vs loadText() in Javascript?

I have a simple JS function that loads text lines to an unordered-list.

Javascript

function loadText() {
    document.getElementById("text1").innerHTML = "Text1";
    document.getElementById("text2").innerHTML = "Text2";
    document.getElementById("text3").innerHTML = "Text3";
}
window.onload = loadText;

HTML

<ul id="textlist">
        <li id="text1"></li>
        <li id="text2"></li>
        <li id="text3"></li>
</ul>

This actually works in the browser(Chrome), but when I use window.onload = loadText(); instead of window.onload = loadText; . I get error:

Uncaught TypeError: Cannot set property 'innerHTML' of null

I assumed it was because the DOM was not read so I tried ondomready but get the same problem there. However changing window.onload = loadText(); back to window.onload = loadText; works again.

Feels a bit weird to me that this would cause a difference. Am I missing something here?

window.onload = loadText();

this immediately executes loadText and stores its return value in window.onlad

window.onload = loadText;

this makes window.onload reference the loadText function. Calling window.onload() will now be the same as calling loadText()

window.onload = loadText; tells the browser to execute loadText when the document was loaded. That means that document.getElementById will be available (and work correctly) in loadText .

window.onload = loadText(); executes loadText immediately and assigns the return value ( undefined ) to window.onload . The assignment is therefore useless and the function won't work.

You want window.onload = loadText here, I have no idea why you even tried window.onload = loadText(); .

window.onload = loadText(); will execute immediately when browser will read the line window.onload = loadText; will assign the value loadText and let the browser load complete dom

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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