无法将属性'src'设置为null [英] Cannot set property 'src' of null

查看:334
本文介绍了无法将属性'src'设置为null的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用javascript旋转图像,我正在尝试在adobes网站上找到的一些代码,这些代码可以完成我想要的工作。当我运行它时它给了我错误:Uncaught TypeError:无法设置属性'src'为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

它每隔5秒间隔重复一次,这是两次之间的时间间隔每个图像

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

这是javascript:

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);
    })();

这里是图片的html:

and here is the html for the image:

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

它显示image1.jpg,但不会旋转它。我有没有看到明显的东西?我不会感到惊讶!

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.

推荐答案

当在时(查看控制台):

When in the head (look at the console):

http://jsfiddle.net/m2wce/

这是因为你是宣布关闭并立即执行。当您在 head 中执行它时, DOM尚未就绪(换句话说,下面的HTML仍未被挂载浏览器,因为它按顺序处理页面,从顶部到僵尸程序),并且在执行时, img 标记尚不存在(因为它在HTML页面。

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).

正文中,在引用的 img ,它有效:

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

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

这篇关于无法将属性'src'设置为null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆