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

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

setAttribute('src','page.html') is not working

javascript

提问by Amarundo

I have the following JavaScript to rotate pages in a iframetag 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 srcattribute of my iframetag.

循环、间隔等正在工作。但是,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 srcproperty. Check that elemt.tagNamegives 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 setPagegets called, the value iis undefined; if you want the value of ito be held from call to call, you need to set it in a closure:

正如你现在拥有它,每次setPage被调用,该值iundefined; 如果您希望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.

您还可以对其进行一些其他调整,但这应该可以使其运行。