简体   繁体   中英

How to set the value for an HTML element from external javascript

I'm using an external javascript file (eg: myjs.js ) with function setval() to set the innerText property of a HTML lable.

I have PHP page with <lable id="abc"></lable> and I have included myjs.js in <head> section. myjs.js is included in <head> section of one more PHP file and I'm calling setval() from this file, so when it runs it must set the innerText of lable in the first PHP file.

Is it possible to achieve? Any suggestions are greatly appreciated. I hope I made question clear.

Thanks

Ideally, move your include of myjs.js to the bottom of the page (just before or after the closing </body> tag). Then it's just:

document.getElementById("abc").innerText = /* ...the text */;

Live example | source

If you can't move the include for some reason, you can put the above code in a function, eg:

function updateTheLabel() {
    document.getElementById("abc").innerText = /* ...the text */;
}

...and then put this script just after the label:

<label id="abc"></label>
<script>
updateTheLabel();
</script>

Live example | source

If you don't want to do that (and it's a bit ugly, mixing script tags into your markup like that), you could wait for some kind of event that occurs when the page is ready. Search for "javascript dom ready event" and you'll see a lot of discussion of this, and lots of solutions. If you're using a library jQuery , Prototype , or any of several others , odds are high (but not 100%) that the library will have something for you. You probably don't want to wait for the window load event, because that fires very late in the page load process (after all external resources — images and such — are loaded).

(Can't do a live example of the above without knowing what library, if any, you're using; but again, there are dozens of "dom ready" solutions out there.)

Or I suppose worst case, you could poll, using this in myjs.js :

function updateTheLabel() {
    var elm = document.getElementById("abc");
    if (elm) {
        elm.innerText = /* ...the text */;
    }
    else {
        setTimeout(updateTheLabel, 50);
    }
}
setTimeout(updateTheLabel, 0);

Live example | source

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