使用jQuery更改iFrame的HTML?

Ste*_* Ou 29 iframe jquery

有没有办法使用jQuery操纵来自同一域的iframe的HTML?

谢谢您的帮助.

小智 24

您必须解析iframe内容.

$("#frameid").contents().find("div").html('My html');
Run Code Online (Sandbox Code Playgroud)

更多信息:http://api.jquery.com/contents/

  • @Stephen Ou:我有点困惑,为什么这个答案有+5而且我的0尽管提供了完全相同的解决方案,但无论如何......你实际上并没有对你发布的那个片段中的HTML做任何事情.如果你想设置你的div的HTML,你需要将一个字符串传递给`html()`函数,例如:`html("new HTML")`.你在你的代码片段中做的是获取div的HTML(无论如何都是空的)并且没有对它做任何事情. (3认同)
  • 似乎由于某些原因不起作用.我的代码`<html> <head> <script src ="http://code.jquery.com/jquery-latest.js"> </ script> <script type ="text/javascript"> $(document). ready(function(){$("#frameDemo").contents().find("div").html();}); </ script> </ head> <body> <iframe src ="iframe. html"id ='frameDemo'></iframe> </ iframe> </ body> </ html>`和iframe:`<html> <head> </ head> <body> <div> </ div> </ body> </ html>` (2认同)

Tow*_*own 21

你可以contents()用来操纵的内容iframe.

$("#frameDemo").contents().find("div").html("new HTML content goes here");
Run Code Online (Sandbox Code Playgroud)


Sha*_*hin 7

以下是jQuery文档中的示例:

<!DOCTYPE html>
<html>
<head>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<body>
  <iframe src="http://api.jquery.com/" width="80%" height="600" id='frameDemo'></iframe> 
<script>$("#frameDemo").contents().find("a").css("background-color","#BADA55");</script>

</body>
</html>
Run Code Online (Sandbox Code Playgroud)


sha*_*nth 5

如果要更改<body>iframe标记内的内容,可以使用以下代码:

$("#iframe_id").contents().find("body").html('my_new_content');
Run Code Online (Sandbox Code Playgroud)