简体   繁体   中英

HTML element no defined in Javascript

I have an html element:

<img alt="" src="../Images/ERROR.jpg" id="live1x4" height="288" style="width: 360px;
                                                display: block;" /

If i refer to this control in javascript which is in the same html page:

live1x4.src = src;

Where src is the location of an image the script works.

If move that javascript to an external js file I get 'live1x4' is undefined.

This occurs ONLY in Internet Explorer.

Wjat can be causing this error?

您必须定位您的元素,而不仅仅是引用ID:

document.getElementById("live1x4").src  = ....

The reason is that the JavaScript code is executed before the img element has been parsed. Whether this happens depends on many things. There are different ways to ensure that it does not happen. A simple way is to wrap your code inside an even handler that is triggered after the document has been loaded:

window.onload = function() {
   // your code here, here all elements are available, e.g.:
   live1x4.src = src;
}

It is generally regarded as bad coding style to use id attribute values as if they were global variables (partly because they stop working ifsynonymous global variables are added), so document.getElementById("live1x4") is preferable to live1x4 . However, this is a different topic.

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