change iframe content jquery

不羁岁月 提交于 2019-12-19 03:56:45

问题


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

<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


回答1:


<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.




回答2:


Check this Demo 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.

jQuery

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

HTML

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

Use .replaceWith() jQuery Method.




回答3:


use document.ready

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


来源:https://stackoverflow.com/questions/22913577/change-iframe-content-jquery

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!