在我的应用程序中,添加了代码以将 div 元素动态附加到其父 div 元素。我可以使用 $('#FrameId').contents().find('#id');
访问预定义的 iframe div 元素。但是当我尝试获取新附加的 div 元素时,它显示未定义。为什么我无法访问新添加的 div 元素?
要附加新的 div 元素,请使用以下代码:
$('#frameId').contents().find("#id").append("<div class="sample">Some text</div>");
当我尝试获取新添加的 div 元素时,使用以下代码:
$('#frameId').contents().find(".sample").click(function(){});
其中,没有触发click事件,因为它找不到.sample div元素。
最佳答案
您可以使用 iframe load事件请参阅以下示例以了解更多信息。
对于动态创建的元素上的单击事件,您必须使用 on(). 创建“委托(delegate)”绑定(bind)
Delegated events have the advantage that they can process events from descendant elements that are added to the document at a later time.
$('#frameId').on('load', function(){
$(this).contents().find('body').on('click', '.sample', function(e){
//Do some stuff
});
});
关于javascript - 从 iframe 动态创建的元素上的事件绑定(bind),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44567317/