【问题标题】:How to interact with the content of an iframe using js or jQuery如何使用 js 或 jQuery 与 iframe 的内容进行交互
【发布时间】:2013-02-22 17:20:22
【问题描述】:

带有此代码的index.html

<iframe src="other.html" width="100%" height="600px"></iframe>

<input type="button" id="btnOutside" value="Click me"/>

在 other.html 我有这个代码:

<input type="button" id="btnInside" value="Other Click"/>
<script type="text/javascript">
$(document).ready(function() {
    $("#btnInside").click(function () {
        alert('inside');
    });
});
</script>

我试图让外部按钮在 index.html 中像这样触发内部按钮

<script type="text/javascript">
$(document).ready(function() {
    $("#btnOutside").click(function () {
        $("#btnInside").click();
    });
});
</script>

但它不起作用。我该怎么办??

【问题讨论】:

    标签: jquery iframe


    【解决方案1】:

    不同的 iframe 具有不同的上下文和文档:当您调用 $('#btnInside') 时,jQuery 正在主机 iframe 中执行并查看该文档,因此无法找到它。但是,如果嵌套 iframe 在同一台服务器上,您可以从主文档通过隧道访问其文档:

    $(document).ready(function() {
        $("#btnOutside").click(function () {
            $('iframe[src="other.html"]').contents().find("#btnInside").click();
        });
    });
    

    【讨论】:

      猜你喜欢
      • 2020-08-09
      • 2011-01-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-05-31
      • 2021-08-22
      相关资源
      最近更新 更多