【问题标题】:Change HTML of an iFrame with jQuery?使用 jQuery 更改 iFrame 的 HTML?
【发布时间】:2011-08-20 23:06:21
【问题描述】:

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

感谢您的帮助。

【问题讨论】:

    标签: jquery iframe


    【解决方案1】:

    您必须解析 iframe 内容。

    $("#frameid").contents().find("div").html('My html');
    

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

    【讨论】:

    • 由于某些原因似乎不起作用。我的代码<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>
    • @Stephen Ou:我有点困惑为什么这个答案有 +5 而我的有 0 尽管提供了完全相同的解决方案,但无论如何......你实际上并没有做任何事情您发布的那个 sn-p 中的 HTML。如果要设置 div 的 HTML,则需要将字符串传递给 html() 函数,例如:html("new HTML")。您在 sn-p 中所做的是获取 div 的 HTML(无论如何都是空的)并且不对其进行任何操作。
    【解决方案2】:

    您可以使用contents() 来操作iframe 的内容。

    $("#frameDemo").contents().find("div").html("new HTML content goes here");
    

    【讨论】:

      【解决方案3】:

      这是来自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>
      

      【讨论】:

        【解决方案4】:

        如果要更改 iframe 的 &lt;body&gt; 标签内的内容,可以使用以下代码:

        $("#iframe_id").contents().find("body").html('my_new_content');
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2023-01-01
          • 2017-03-12
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多