如何为新注入的html附加jquery事件处理程序?

如果没有生成 HTML,我该如何使用.on()? jQuery页面

If new HTML is being injected into the page,select the elements and attach event handlers after the new HTML is placed into the page.

但我不太确定如何做到这一点.有没有办法“重新加载”事件处理程序?

所以如果我有

$(document).ready(function(){
    $('.test').on('click',function(){
        var id = $(this).attr('id');
        console.log("clicked" + id);
    });
generatePage();
});

其中generatePage()创建了一堆与.test的div,我将如何重新绑定.on()?

我知道类似的问题已经被问到,但我没有找到我正在寻找的快速搜索.

解决方法

使用.on,如下面的例子.可以假设body标签总是可用的,因此可以安全地将事件处理程序附加到正文,并将事件委托给选择器,在这种情况下.test.
$(document).ready(function(){
    $('body').on('click','.test',function(){ // Make your changes here
        var id = $(this).attr('id');
        console.log("clicked" + id);
    });

    generatePage();
});

或者如果generatePage()也生成html,head和body标签使用document作为选择器.

$(document).ready(function(){
    $(document).on('click',function(){ // Make your changes here
        var id = $(this).attr('id');
        console.log("clicked" + id);
    });

    generatePage();
});

根据jquery documentation .on接受以下参数:

.on( events [,selector] [,data],handler(eventObject) )

包括选择器描述如下:

When a selector is provided,the event handler is referred to as delegated. The handler is not called when the event occurs directly on the bound element,but only for descendants (inner elements) that match the selector. jQuery bubbles the event from the event target up to the element where the handler is attached (i.e.,innermost to outermost element) and runs the handler for any elements along that path matching the selector.

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


Mip是什么意思以及作用有哪些
怎么测试Mip页面运行情况
MIP安装的具体步骤有哪些
HTML添加超链接、锚点的方法及作用详解(附视频)
MIP的规则有哪些
Mip轮播图组件中的重要属性讲解
Mip的内联框架组件是什么
怎么创建初始的MIP配置及模板文件
HTML实现多选框及无法提交多数据的原因分析(附视频)
HTML如何设置复选框、单选框以及默认选项?(图文+视频)
怎么使用MIP组件
Div垂直居中效果怎么实现
HTML如何实现视频在线播放
如何使用Mip代码校验工具
Mip中弹出层组件是什么
如何用HTML实现简单按钮样式
Mip中快速回顶组件怎么用
Div内容居中效果如何实现
Div水平居中效果怎么实现
Mip中列表组件怎么用