如何使用jquery操作iframe对象

How to manipulate iframe objects using jquery

本文关键字:iframe 对象 操作 jquery 何使用      更新时间:2023-09-26

我已经经历了很多与这个问题相关的主题,但无法获得所需的输出。

我在里面调用一个 iframe 和 html,如下所示:

 <iframe class="full-screen-preview__frame" id="nitseditpreview" src="himu/index.php" name="preview-frame" frameborder="0" noresize="noresize" data-view="fullScreenPreview">

假设在这个 iframe 中,我有一个带有如下类名的 h2 标签:

<body>
  <section id="about-us">
    <div class="container">
      <div class="text-center">
        <div class="col-sm-8">
          <h2 class="maincontent">
  Why with Us
  </h2>
        </div>
      </div>
    </div>
  </section>
</body>

如浏览器中的检查元素所示

通过使用Jquery,我想操纵它,例如我想在其中放置边框。我已经尝试了很多东西,但我想如果有人修复错误,这个东西会起作用,我的 jquery 看起来像这样:

$(document).load(function () {
$('#nitseditpreview').load(function () { //The function below executes once the iframe has finished loading
    $this = $(this);
    $('#nitsmenu', this.contents()).css('border', 'solid 1px #777');
});

});

不知道我哪里做错了,即使我也遵循同源政策。

如果框架文档和框架文档位于同一域中,则不需要沙盒属性或 CORS 箍跳。但是这里还有许多其他错误:

  • $(document).load(...)应该是$(document).ready(...)的(因为它在脚本运行时已经加载)
  • 您定义了$this = $(this),但在下一行中尝试使用裸this
  • 您正在尝试匹配框架文档中似乎不存在的#nitsmenu

以下内容似乎有效,尽管我担心该 iframe 的.load()上可能仍然存在竞争条件:

$(document).ready(function() {
  $('#nitseditpreview').load(function() {
      $(this).contents().find('.container').css('border', 'solid 1px #777');
  });
});

http://plnkr.co/edit/tCEHdU0ckg5q4w4tPVFU