所以,我正在尝试使用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中的元素?
答案 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/