使用Javascript访问IFrame srcdoc中的元素

时间:2015-08-30 11:50:19

标签: javascript jquery iframe

所以,我正在尝试使用jQuery / javascript在iframe srcdoc中获取一个元素,并说,附加一个单击处理程序。 e.g ..

<iframe id="iframe" srcdoc="<html><head></head><body><input type="button" id="button" /></body></html>"></iframe>

以下代码不起作用:

$("#iframe").find("#button").on("click", function{ alert('clicked'); });

也不使用$(“#iframe”)。contents()或其他几种方法。

如何将事件处理程序附加到Iframe srcdoc中的元素?

1 个答案:

答案 0 :(得分:0)

JS处理点击:

$("#iframe").contents().find("body").find("#button").click(function() {alert('clicked')});

HTML更改:

<iframe id="iframe" srcdoc="<html><head></head><body><input type='button' id='button' /></body></html>"></iframe>

编辑:使用JS加载iframe:

$("#container").append($("<iframe />").attr({"srcdoc":"<html><head></head><body><input type='button' id='button' /></body></html>", "id":"iframe" })); 

$("#iframe").load( function() {
    $("#iframe").contents().find("body").find("#button").click(
        function () {alert('clicked')}
    );
});

工作小提琴链接:http://jsfiddle.net/hufrmcLt/

编辑:http://jsfiddle.net/hufrmcLt/1/