javascript 未捕获的 TypeError 无法将属性“src”设置为 null
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11729915/
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
Uncaught TypeError cannot set property 'src' of null
提问by Ilan Biala
So on my new websitein google chrome, I am trying to make the images switch every 5 seconds using a setInterval function. This seems to work, however I have the problem cannot set property src of null.
所以在我的谷歌浏览器新网站上,我试图使用 setInterval 函数每 5 秒切换一次图像。这似乎有效,但是我的问题是无法将属性 src 设置为 null。
var images = new Array();
images[0] = "/images/grilled-chicken-large.png";
images[1] = "/images/sizzly-steak.png";
var img = document.getElementById("img");
function changeImage() {
for (var i = 0; i < 3; i++) {
img.src = images[i];
if (i == 2){i = i - 2;};
}
}
window.onload=setInterval("changeImage()", 5000);
I know the problem is that I am trying to get the element with an id of img before the page is done loading, but I've already got a window.onload, so i don't know what to do. Also, if i make an init() function containing the setInterval and the img variable, the page freezes.
我知道问题是我试图在页面加载完成之前获取 id 为 img 的元素,但我已经有了 window.onload,所以我不知道该怎么做。另外,如果我创建一个包含 setInterval 和 img 变量的 init() 函数,页面会冻结。
Any ideas?
有任何想法吗?
回答by Yogu
The problem is that you access element 2
of an array with only two elements (0 and 1).
问题是您访问2
只有两个元素(0 和 1)的数组元素。
But there is also a logical error in your script: Where do you store the index of the currently visible image? You need a global variable which holds that index.
但是您的脚本中也存在逻辑错误:您将当前可见图像的索引存储在哪里?您需要一个保存该索引的全局变量。
var currentIndex = 0;
function changeImage() {
// Switch currentIndex in a loop
currentIndex++;
if (currentIndex >= images.length)
currentIndex = 0;
var img = document.getElementById("img");
img.src = images[currentIndex];
}
document.onload = function() {
setInterval(changeImage, 5000);
}
I've moved the img
variable into the function so that it is assigned after five seconds when the document has loaded.
我已将img
变量移动到函数中,以便在文档加载五秒后对其进行分配。
Just to clear things up: JavaScript is an event-based programming language. That means that the slideshow-change code is executed every time the interval fires, does some work (switch to the next slide) and then is done, so that the browser can render the page. If you iterate through the slides in a loop, there is no way for the browser to show the new slide because the script is still executing between the slides. The solution is what I've posted: Define a global variable that replaces the loop variable, and increment it every time the next slide is to be shown.
澄清一下:JavaScript 是一种基于事件的编程语言。这意味着每次间隔触发时都会执行幻灯片更改代码,执行一些工作(切换到下一张幻灯片)然后完成,以便浏览器可以呈现页面。如果循环遍历幻灯片,浏览器将无法显示新幻灯片,因为脚本仍在幻灯片之间执行。解决方案是我发布的内容:定义一个全局变量来替换循环变量,并在每次显示下一张幻灯片时增加它。
回答by ?ime Vidas
Here:
这里:
window.onload = function () {
var images = [
'http://placekitten.com/100/200',
'http://placekitten.com/200/100',
];
var img = document.getElementById( 'img' );
setInterval(function () {
img.src = img.src === images[0] ? images[1] : images[0];
}, 1000 );
};
Live demo:http://jsfiddle.net/wkqpr/
现场演示:http : //jsfiddle.net/wkqpr/
If you have more than two images, you can do this:
如果你有两个以上的图像,你可以这样做:
window.onload = function () {
var images = [
'http://placekitten.com/100/200',
'http://placekitten.com/200/100',
'http://placekitten.com/200/150',
'http://placekitten.com/150/300'
];
images.current = 0;
var img = document.getElementById( 'img' );
setInterval(function () {
img.src = images[ images.current++ ];
if ( images.current === images.length ) images.current = 0;
}, 1000 );
};
Live demo:http://jsfiddle.net/wkqpr/1/
现场演示:http : //jsfiddle.net/wkqpr/1/
回答by spaceman12
function changeImage()
{
for (var i = 0; i < 2; i++)
{
img.src = images[i];
}
}
window.onload=function()
{
setInterval(changeImage,5000);
}
Your last line in the for loop is completely useless and just complicate things, Also, Your way of setting a window onload event is not standard!
您在 for 循环中的最后一行完全没用,只会使事情复杂化,此外,您设置窗口 onload 事件的方式不是标准的!
EDIT: the src
property is null because , obviously, your array size is only 2!!
编辑:该src
属性为空,因为很明显,您的数组大小仅为 2!
回答by Nicolas Stamm
Your for loop looks odd. Try that loop:
你的 for 循环看起来很奇怪。试试这个循环:
function changeImage(){
if(!img.attributes["index"]){img.attributes["index"]=0;return;};
img.attributes["index"]++;
img.src=images[img.attributes["index"]];
}
window.onload=function(){
window.img=document.getElementById("img");
setInterval("changeImage()",5000)
}
Should work.
You'll notice that I store the image index in an attribute of the image, as opposed to
a global variable. I think the global is slightly faster, but storing it in the image
means you can easily expand this to multiple images if needed.
Also, the problem with your browser freezing was that the following code:
应该管用。
您会注意到我将图像索引存储在图像的属性中,而不是全局变量中。我认为全局稍微快一点,但是将其存储在图像中意味着您可以根据需要轻松地将其扩展为多个图像。此外,您的浏览器冻结的问题在于以下代码:
for(var i=0;i<3;i++){
//Some more stuff
if(i==2){i-=2};
}
This loop is infinite, because whenever i
reaches 2
, i==2
becomes true, which means that iteration will reset i
to 0
and start it all over again. The only way to prevent that would be a break;
somewhere, which I don't see anywhere.
Tip: It is generally a bad idea to tamper with the index variable in for loops.
这个循环是无限的,因为只要i
达到2
,i==2
就会变为真,这意味着迭代将重置i
为0
并重新开始。防止这种情况的唯一方法是break;
某个地方,我在任何地方都看不到。提示:在 for 循环中篡改索引变量通常是一个坏主意。