How to interact with the content of an iframe using js or jQuery

梦想的初衷 提交于 2019-12-22 09:56:37

问题


index.html with this code

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

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

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>

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??


回答1:


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();
    });
});


来源:https://stackoverflow.com/questions/15029790/how-to-interact-with-the-content-of-an-iframe-using-js-or-jquery

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!