javascript setAttribute('src','page.html') 不起作用
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15574305/
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
setAttribute('src','page.html') is not working
提问by Amarundo
I have the following JavaScript to rotate pages in a iframe
tag every 5 seconds.
我有以下 JavaScriptiframe
每 5 秒在标签中旋转页面。
function setPage() {
if (i == pages.length) {
i = 0;
}
alert(pages[i]); //verify the right url is there
var elmnt = document.getElementById('dashboard');
elmnt.setAttribute('src', pages[i]);
i++;
}
setInterval("setPage()", 5000);
The loop, interval, etc., is working. However, nothing changes for the src
attribute of my iframe
tag.
循环、间隔等正在工作。但是,src
我的iframe
标签属性没有任何变化。
I tested with both IE8 and Chrome.
我用 IE8 和 Chrome 进行了测试。
What am I doing wrong? How can I accomplish that (no jQuery...)
我究竟做错了什么?我怎样才能做到这一点(没有 jQuery ...)
回答by VisioN
I'd suggest you to use elmnt.src = pages[i]
instead.
我建议你elmnt.src = pages[i]
改用。
If it still gives you error, then most probably you are trying to target element, that doesn't have src
property. Check that elemt.tagName
gives you IFRAME
.
如果它仍然给您错误,那么很可能您正在尝试定位没有src
属性的元素。检查elemt.tagName
给你IFRAME
。
回答by Paul Gleeson
Have you tried just manually setting the src property of the iframe?
您是否尝试过手动设置 iframe 的 src 属性?
document.getElementById('dashboard').src = pages[i];
回答by ultranaut
As you have it now, each time setPage
gets called, the value i
is undefined
; if you want the value of i
to be held from call to call, you need to set it in a closure:
正如你现在拥有它,每次setPage
被调用,该值i
是undefined
; 如果您希望i
从呼叫到呼叫都保持的值,则需要将其设置在闭包中:
var setPage = (function () {
var i = 0;
return function () {
if (i == pages.length) {
i = 0;
}
var elmnt = document.getElementById('dashboard');
elmnt.setAttribute('src', pages[i]);
i++;
}
}());
Also when setting the interval, the first argument should just be the name of the function, no quotes or parens:
同样在设置间隔时,第一个参数应该只是函数的名称,没有引号或括号:
setInterval(setPage, 5000);
There's a couple other tweaks you could make to it, but that should get it running.
您还可以对其进行一些其他调整,但这应该可以使其运行。