【发布时间】:2011-08-20 23:06:21
【问题描述】:
有没有办法使用 jQuery 来操作来自同一域的 iframe 的 HTML?
感谢您的帮助。
【问题讨论】:
有没有办法使用 jQuery 来操作来自同一域的 iframe 的 HTML?
感谢您的帮助。
【问题讨论】:
您必须解析 iframe 内容。
$("#frameid").contents().find("div").html('My html');
【讨论】:
<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> </body> </html> 和 iframe:<html> <head> </head> <body> <div></div> </body> </html>
html() 函数,例如:html("new HTML")。您在 sn-p 中所做的是获取 div 的 HTML(无论如何都是空的)并且不对其进行任何操作。
您可以使用contents() 来操作iframe 的内容。
$("#frameDemo").contents().find("div").html("new HTML content goes here");
【讨论】:
这是来自the jQuery documentation的示例:
<!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>
【讨论】:
如果要更改 iframe 的 <body> 标签内的内容,可以使用以下代码:
$("#iframe_id").contents().find("body").html('my_new_content');
【讨论】: