如何使用 jquery 动态更改 iframe 中的内容?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1554396/
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-08-26 11:42:25  来源:igfitidea点击:

How do I dynamically change the content in an iframe using jquery?

jqueryiframe

提问by Audun

I was wondering if it is possible to have a site with an iframe and some jquery code that changes the iframe content every 30 seconds. The content is in different webpages.

我想知道是否有可能有一个带有 iframe 的站点和一些每 30 秒更改一次 iframe 内容的 jquery 代码。内容在不同的网页中。

Something like this:

像这样的东西:

<html>
  <head>
    <script type="text/javascript" src="jquery.js"></script>
    <script>
      $(document).ready(function(){
        var array = new array();
        array[0] = 'http://webPage1.com';
        array[1] = 'http://webPage2.com';
        // And so on.
        // Do something here to change the iframe every 30 second
      });
    </script>
  </head>
  <body>
    <iframe id="frame"></iframe>
  </body>
</html>

回答by Anatoliy

<html>
  <head>
    <script type="text/javascript" src="jquery.js"></script>
    <script>
      $(document).ready(function(){
        var locations = ["http://webPage1.com", "http://webPage2.com"];
        var len = locations.length;
        var iframe = $('#frame');
        var i = 0;
        setInterval(function () {
            iframe.attr('src', locations[++i % len]);
        }, 30000);
      });
    </script>
  </head>
  <body>
    <iframe id="frame"></iframe>
  </body>
</html>

回答by Anthony

If you just want to change where the iframe points to and not the actual content inside the iframe, you would just need to change the srcattribute.

如果您只想更改 iframe 指向的位置而不是 iframe 内的实际内容,则只需更改该src属性。

 $("#myiframe").attr("src", "newwebpage.html");

回答by geowa4

var handle = setInterval(changeIframe, 30000);
var sites = ["google.com", "yahoo.com"];
var index = 0;

function changeIframe() {
  $('#frame')[0].src = sites[index++];
  index = index >= sites.length ? 0 : index;
}