【问题标题】:How to change iframe source using javascript如何使用 javascript 更改 iframe 源
【发布时间】:2019-12-29 15:25:46
【问题描述】:

我正在设置一个 iframe 来嵌入来自服务器的流式视频,它运行良好。 当用户单击标签以更新 iframe 并更改其来源时,我需要它。 它也适用于我桌面上的不同浏览器,但不适用于移动设备。 用户单击标签后,iframe 变为空并仅在移动设备浏览器上显示(未找到)此案例。 有什么解决办法吗?

我搜索了很多答案,所有这些都为移动浏览器提供了相同的结果。 我也尝试使用 javascript 函数来更新 iframe 的来源。

iframe:

<iframe name="iframe1" id="frameid" style="width:600px; height:480px;" allowfullscreen src="http://serverip:8080/cc/embed.html"></iframe>

更新 iframe 来源的链接:

<a href="#" onclick="update('http://serverip:8080/test.html')">

javascript函数:

<script>
  function update(loc) {
    document.getElementById('frameid').src = loc;
  }
  </script>

我也尝试重新加载 iframe,但它也不起作用:

function update2(loc) {
     document.getElementById('frameid').src = loc;
     document.getElementById('frameid').contentWindow.location.reload(true);
  }

我还尝试在单击链接时创建一个新的 iframe,它会创建一个新的 iframe 但也是空的,也显示(未找到)。

【问题讨论】:

    标签: javascript php html iframe embed


    【解决方案1】:

    你可以这样做:

    <a href="http://www.google.com/" onclick="return loadIframe(this.href);">Page 1</a>
    <a href="http://www.apple.com/" onclick="return loadIframe(this.href);">Page 2</a>
    
    <iframe name="frameid" id="frameid" src="http://www.microsoft.com/" frameborder="0">
            Your browser doesn't support iframes.
        </iframe>
    
    function loadIframe(url) {
      $("#frameid").attr('src',url);
      return false;
    }
    

    【讨论】:

    • 刚刚尝试过,但在我的情况下也不起作用。我想我需要一种方法来重新加载更新 iframe 源的整个页面,但我真的不知道这样做的正确方法。谢谢你的回答。
    【解决方案2】:

    你在正确的轨道上。

    这条线确实有效:

    document.getElementById('myFrame').src = 'https://yournewurl.com';
    

    不要在链接上使用 onclick 属性,而是尝试像这样添加事件监听器:

    document.getElementById('myLink').addEventListener('click', () => {
    // change src attribute of iframe
    document.getElementById('myFrame').src = 'https://yournewurl.com';
    })
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-05-12
      • 1970-01-01
      • 2012-07-04
      • 1970-01-01
      相关资源
      最近更新 更多