Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

javascript - Cannot set property 'src' of null

I am trying to rotate an image using javascript and I was trying some code I found on adobes website that does what I was looking for. When I run it it gives me the error: Uncaught TypeError: Cannot set property 'src' of null

It keeps repeating every 5 second interval which is the amount of time between each image

Here is the javascript:

 (function () {
        var rotator = document.getElementById('rotator');  // change to match image ID
        var imageDir = 'images/';                          // change to match images folder
        var delayInSeconds = 5;                            // set number of seconds delay
        // list image names
        var images = ['image2.jpg', 'image3.jpg', 'image4.jpg', 'image1.jpg'];

        // don't change below this line
        var num = 0;
        var changeImage = function () {
            var len = images.length;
            rotator.src = imageDir + images[num++];
            if (num == len) {
                num = 0;
            }
        };
        setInterval(changeImage, delayInSeconds * 1000);
    })();

and here is the html for the image:

<img src="images/image1.jpg" alt="rotating image" width="400" height="300" id="rotator" />

It shows the image1.jpg, but does not rotate it. Is there something blatantly obvious that I am not seeing? Wouldn't surprise me!

Thanks to anyone that can offer advice.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

When in the head (look at the console):

http://jsfiddle.net/m2wce/

This happens because you are declaring the closure and executing right away. When you execute it in the head, the DOM is not ready (in other words, the HTML below still hasn't been "mounted" by the browser, as it processes the page sequencially, from top to botto) and at the time of the execution the img tag does not yet exist (because it is down below in the HTML page).

When in the body, after the referenced img, it works:

http://jsfiddle.net/m2wce/1/


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...