更改iframe内容jquery

Ajo*_*uve 3 html javascript iframe jquery

我想更改我的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>
Run Code Online (Sandbox Code Playgroud)

使用此代码我总是有我的谷歌页面而不是喜欢的ifram

Mic*_*xon 5

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

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

编辑:

唯一的方法是执行@ user1153551所做的操作并替换整个文档.


Jay*_*tel 5

检查这个演示jsFiddle

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

jQuery

$('#frame').load(function() {
  $('#frame').replaceWith('<p>hi</p>');
});
Run Code Online (Sandbox Code Playgroud)

HTML

<iframe id="frame" width="100%" height="95%" src="http://w3schools.com"></iframe>
Run Code Online (Sandbox Code Playgroud)

使用.replaceWith() jQuery 方法。