最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - setAttribute('src','page.html') is not working - Stack Overflow

programmeradmin4浏览0评论

I have the following JavaScript to rotate pages in a iframe tag every 5 seconds.

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.

I tested with both IE8 and Chrome.

What am I doing wrong? How can I acplish that (no jQuery...)

I have the following JavaScript to rotate pages in a iframe tag every 5 seconds.

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.

I tested with both IE8 and Chrome.

What am I doing wrong? How can I acplish that (no jQuery...)

Share Improve this question asked Mar 22, 2013 at 15:39 AmarundoAmarundo 2,39716 gold badges52 silver badges70 bronze badges 8
  • Have you tried elmnt.src = pages[i]? – VisioN Commented Mar 22, 2013 at 15:40
  • Rather verify that elmnt is there. Do you get any errors in the console? – Bergi Commented Mar 22, 2013 at 15:41
  • @VisioN - yes, I did: "Object doesn't support this property or method" – Amarundo Commented Mar 22, 2013 at 16:03
  • @Amarundo It means that elmnt is not the element you require. – VisioN Commented Mar 22, 2013 at 16:04
  • @Bergi - no errors - I even alert(elmnt.id) and I get "dashboard" – Amarundo Commented Mar 22, 2013 at 16:04
 |  Show 3 more ments

3 Answers 3

Reset to default 2

I'd suggest you to use elmnt.src = pages[i] instead.

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.

Have you tried just manually setting the src property of the iframe?

document.getElementById('dashboard').src = pages[i];

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:

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.

发布评论

评论列表(0)

  1. 暂无评论