javascript 无法将属性“src”设置为 null

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17237142/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 07:34:33  来源:igfitidea点击:

Cannot set property 'src' of null

javascript

提问by Joe W

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

我正在尝试使用 javascript 旋转图像,并且正在尝试在 adobes 网站上找到的一些代码,这些代码可以满足我的需求。当我运行它时,它给了我错误:Uncaught TypeError: Cannot set property 'src' of null

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

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

Here is the javascript:

这是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:

这是图像的html:

<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!

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

Thanks to anyone that can offer advice.

感谢任何可以提供建议的人。

回答by acdcjunior

When in the head(look at the console):

head(查看控制台)中时:

http://jsfiddle.net/m2wce/

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 imgtag does not yet exist (because it is down below in the HTML page).

发生这种情况是因为您正在声明闭包并立即执行。当您在 中执行它时headDOM 还没有准备好(换句话说,下面的 HTML 还没有被浏览器“挂载”,因为它从上到下按顺序处理页面)并且在执行img标记尚不存在(因为它在 HTML 页面下方)。

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

在 中时body,在引用之后img,它的工作原理是:

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

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

回答by Sanjeev Rai

You need to place this code after your dom gets ready. i.e inside $(document).ready()or on window.onload. as:

您需要在您的 dom 准备好后放置此代码。即里面$(document).ready()或上window.onload。作为:

window.onload=function(){
(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);
})();

If you place that code inside anynomous function inside head (as you did), then it will not be able to load that image element from Dom because Dom would not be fully loaded at that time.

如果您将该代码放在 head 内的 anynomous 函数中(就像您所做的那样),那么它将无法从 Dom 加载该图像元素,因为那时 Dom 不会完全加载。

回答by bdesham

Your script is loaded before the body of your page, so the rotatorelement is not found. Remove the var rotator = ...line and put it inside the changeImagefunction instead:

您的脚本在页面正文之前加载,因此rotator未找到该元素。删除该var rotator = ...行并将其放入changeImage函数中:

(function () {
    var rotator;
    var rotatedImageId = 'rotator';           // change to match your HTML
    var imageDir = 'images/';
    var delayInSeconds = 5;
    // 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 () {
        if (!rotator)
            rotator = document.getElementById(rotatedImageId);
        if (!rotator)
            return;

        var len = images.length;
        rotator.src = imageDir + images[num++];
        if (num == len) {
            num = 0;
        }
    };
    setInterval(changeImage, delayInSeconds * 1000);
})();

回答by GoodBoyth

I met this problems too.You can make document.getElementById(rotatedImageId)before you use that function. Another word,you can define rotator to gobal. This is how i solved this problem.

我也遇到了这个问题。你可以document.getElementById(rotatedImageId)在使用该功能之前制作。换句话说,您可以将 rotator 定义为 gobal。这就是我解决这个问题的方法。