4

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>

但这是行不通的。我能做些什么??

4

1 回答 1

10

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

$(document).ready(function() {
    $("#btnOutside").click(function () {
        $('iframe[src="other.html"]').contents().find("#btnInside").click();
    });
});
于 2013-02-22T17:27:11.997 回答