javascript - 从 iframe 动态创建的元素上的事件绑定(bind)

标签 javascript jquery html iframe

在我的应用程序中,添加了代码以将 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/

相关文章:

html - iframe 中的内容会重定向,但不会重定向整个页面

javascript - 使用 Google App Script 修改 Google Sheet 中的单元格

javascript - Typescript 导入 - 每个文件一个类约定

javascript - 设置 Overflow=visible 时如何为 div 赋予不透明度

javascript - 在 JavaScript 中过滤 JSON 对象列表的最高性能方法是什么?

javascript - 使用 jQuery 构建动态表单部件

javascript - 在 contenteditable div 中的光标处追加 div

javascript - 无法访问值标签以在 jquery 、 mysql 、 php 中显示数据

javascript - 如何获得 td 元素相对父 tr 元素的顶部偏移量?

javascript - 禁用 create-react-app 的 SKIP_PREFLIGHT_CHECK 有缺点吗?