如何使用js或jQuery与iframe的内容进行交互 [英] How to interact with the content of an iframe using js or jQuery

查看:232
本文介绍了如何使用js或jQuery与iframe的内容进行交互的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

index.html

index.html with this code

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

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

在other.html中我有这段代码:

In the other.html I have this code:

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

我试图让外部按钮触发index.html中的内部按钮

I am trying to make that the outside button trigger the inside button like this in the index.html

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

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

But is is not working. What can I do??

推荐答案

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

Different iframes have different contexts and documents: when you invoke $('#btnInside'), jQuery is executing in the host iframe and looking in that document, so it can't find it. If the nested iframe is on the same server though, you can tunnel through to its document from the host document:

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

这篇关于如何使用js或jQuery与iframe的内容进行交互的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆