简体   繁体   English

如何从内部更改iframe src

[英]how to change iframe src from inside it

I need to change src attribute of iframe after click a button inside the iframe. 单击iframe中的按钮后,我需要更改iframe的src属性。

<button type="button" onclick="ch_src('page2.php')">Submit</button>

<script type='text/javascript'>
function ch_src(loc) 
{ 
var v = document.getElementById('iframe1');
v.src = loc;
}
</script>

(1) when using window.location = loc; (1)使用window.location = loc; it changes the content of iframe but src still pointing to previous page. 它更改了iframe的内容,但src仍指向上一页。
(2) why we need to change src value not only open the new page inside iframe? (2)为什么我们不仅需要在iframe中打开新页面,还需要更改src值? we use JS to print iframe content excluding content outside iframe. 我们使用JS打印iframe内容(不包括iframe外部的内容)。 this script is printing page in src not actual opened page. 此脚本在src中打印页面,而不是实际打开的页面。
(3) above function can't change src mostly coz it can't get element id of itself (iframe) but may be sub elements. (3)上面的函数大部分不能更改src,因为它无法获取本身(iframe)的元素ID,但可能是子元素。
(4) when moving the function outside the iframe, it doesn't execute. (4)将函数移到iframe之外时,它不会执行。 may be due to "same origin policy" 可能是由于“原产地政策相同”

finally we need to click a button in (page1.php) inside iframe causes 最后,我们需要在iframe中点击(page1.php)中的按钮
(1) load (page2.php) into same iframe (1)将(page2.php)加载到同一iframe中
(2) change iframe's src attribute to (page2.php) (2)将iframe的src属性更改为(page2.php)

first include jquery then try this in you page1.php: 首先包含jquery,然后在您的page1.php中尝试:

<script type="text/javascript">
$(document).ready(function(){
  $("iframe").load(function(){
      $(this).contents().find("button").click(function(){
      document.querySelectorAll("iframe").src = "https://example.com/page2.php";
      });
  });
});
</script>

for better detection please paste your page1.php here 为了更好地检测,请在此处粘贴您的page1.php

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

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