javascript 更改 iframe 内容 jquery

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

change iframe content jquery

javascriptjqueryhtmliframe

提问by Ajouve

I'd like to change my iframe content but I don't understand how

我想更改 iframe 内容,但我不明白如何更改

<html>
    <head>
        <title>test</title>
        <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
    </head>
    <body>
        <iframe id="frame" width="100%" height="95%" src="http://google.com"></iframe>
    <script type=text/javascript >
        $('#frame').contents().find( "body" ).html('<p>hi</p>')
    </script>
    </body>

</html>

With this code I always have my google page and not a ifram with hi

使用此代码,我始终拥有我的 google 页面,而不是带有 hi 的 ifra

回答by Michael Coxon

<script type="text/javascript">
  $(document).ready(function(){        
       $('#frame').on('load', function() {
           $(this).contents().find( "body" ).html('<p>hi</p>');
       });
  });
</script>

While this is right, the content will never change as you are trying to modify the body of an external resource. You cannot do this due to cross-site scripting rules.

虽然这是对的,但是当您尝试修改外部资源的主体时,内容永远不会改变。由于跨站点脚本规则,您无法执行此操作。

EDIT:

编辑:

The only way to do it is to do what @user1153551 did and replace the whole document.

唯一的方法是做@user1153551 所做的并替换整个文档。

回答by Jay Patel

Check this Demo jsFiddle

检查这个演示jsFiddle

you have to use load event within the iframe's document and calling out to a load function in the containing document to replace to a body contain.

您必须在 iframe 的文档中使用 load 事件并调用包含文档中的加载函数以替换为包含的正文。

jQuery

jQuery

$('#frame').load(function() {
  $('#frame').replaceWith('<p>hi</p>');
});

HTML

HTML

<iframe id="frame" width="100%" height="95%" src="http://w3schools.com"></iframe>

Use .replaceWith()jQuery Method.

使用.replaceWith()jQuery 方法。

回答by Rituraj ratan

use document.ready

使用document.ready

<script type=text/javascript >
  $(document).ready(function(){        
      $('#frame').on('load', function() {
       $(this).contents().find( "body" ).html('<p>hi</p>');
     });
  });
</script>