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

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

像这样的东西:

<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>
Audun asked 2019-09-10T05:48:02Z
3个解决方案
132 votes
<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>
Anatoliy answered 2019-09-10T05:48:09Z
8 votes

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

 $("#myiframe").attr("src", "newwebpage.html");
Anthony answered 2019-09-10T05:48:33Z
4 votes
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;
}
geowa4 answered 2019-09-10T05:48:50Z
translate from https://stackoverflow.com:/questions/1554396/how-do-i-dynamically-change-the-content-in-an-iframe-using-jquery