简体   繁体   English

使用on将jquery中动态生成的元素上的多个事件处理程序对绑定

[英]Binding multiple event handler pairs on dynamically generated elements in jquery with on

I have some dynamically generated elements with the class my-class on which I want to bind some events. 我的类my-class有一些动态生成的元素,我想在这些元素上绑定一些事件。 I have the below code which works properly. 我有下面的代码,可以正常工作。

$(document).on("event1", ".my-class", function () {
    alert("Event 1");
});

$(document).on("event2", ".my-class", function () {
    alert("Event 2");
});

I want to refactor it so that there can be a single call to on for the category. 我想重构它,这样可以有一个调用on的类别。 Something like this 像这样

$(document).on(".my-class", {      
    "event1": function() {alert("Event1")},
    "event2": function() {alert("Event2")}
});

Is this possible in jquery? 在jQuery中这可能吗?

There might be a better way, but I've used this before and it worked for me: 也许有更好的方法,但是我以前使用过它,对我有用:

Demo Fiddle 演示小提琴

I wouldn't delegate off the document, instead I'd use the closest parent container. 我不会委托该文档,而是使用最近的父容器。

JS: JS:

$('body').on('click mouseenter', 'div', function(e) {
    if (e.type === 'click') {
        $('div').html('clicked');
    }
    else {   //you'd need an else if here if you had more than two event types
        $('div').html('mouse enter');
    }
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM