简体   繁体   English

如何从另一个页面 onclick 更改 iframe 的“src”?

[英]How do I change 'src' of an iframe from another page onclick?

I have two html pages 1.html and 2.html .我有两个 html 页面1.html2.html

I have two buttons on 1.html .我在1.html上有两个按钮。

  • one button links to Google一键链接到谷歌
  • one button links to Facebook一键链接到 Facebook

I have an iframe in 2.html .我在2.html有一个iframe

How do I change the iframe src on 2.html by clicking on a button on 1.html .如何通过单击1.html上的按钮更改2.html上的iframe src

You can use the following您可以使用以下

<!DOCTYPE html>
<html>
    <head>
        <title></title>
        <script>
            function changeSrc(loc) {
                document.getElementById('iframeId').src = loc;
            }
      </script>
    </head>
    <body>
        <button onclick="changeSrc('http://en.wikipedia.org')">Wikipedia</button>
        <button onclick="changeSrc('http://www.bing.com')">Bing</button>
        <iframe id="iframeId" src="" width="100%" height="100%"></iframe>
    </body>
</html>

Hi try following...嗨,请尝试以下...

<button onclick="return (function(){
   var _iframe = document.getElementById('iFrameId');
   _iframe.src = '1.html';
})();">Page 1</button>

<button onclick="return (function(){
   var _iframe = document.getElementById('iFrameId');
   _iframe.src = '2.html';
})();">Page 2</button>

Update更新

This answer was created before SO's change to more secure policies, I have updated the demo by adding a "s" to http of the src.这个答案是在 SO 更改为更安全的策略之前创建的,我通过向 src 的 http 添加“s”来更新演示。 Keep in mind that any interaction with an iframe is subject to security measures of both the website of the iframe and the website within the iframe.请记住,与 iframe 的任何交互都受 iframe 网站和 iframe 内网站的安全措施的约束。

You can use HTML and you don't need CSS or JS/jQ:您可以使用 HTML,并且不需要 CSS 或 JS/jQ:

  • Create an <a> with the href with the url of desired destination.使用所需目的地的 url 创建一个带有href<a>
  • Add a target attribute with the value of the iframe's name attribute.添加具有 iframe name属性值的target属性。

BTW, Google and Facebook busts iframes, so the demonstrations have different sites.顺便说一句,谷歌和 Facebook 破坏了 iframe,所以演示有不同的网站。

PLUNKER普伦克

SNIPPET片段

 <!DOCTYPE html> <html> <head> <style> iframe { width: 97vw; height: 65vh; } </style> </head> <body> <fieldset> <button><a href='https://plainjs.com' target='ifrm1'>PlainJS</a> </button> </fieldset> <iframe name='ifrm1' src='about:blank'></iframe> </body> </html>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM