簡體   English   中英

使用on將jquery中動態生成的元素上的多個事件處理程序對綁定

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

我的類my-class有一些動態生成的元素,我想在這些元素上綁定一些事件。 我有下面的代碼,可以正常工作。

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

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

我想重構它,這樣可以有一個調用on的類別。 像這樣

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

在jQuery中這可能嗎?

也許有更好的方法,但是我以前使用過它,對我有用:

演示小提琴

我不會委托該文檔,而是使用最近的父容器。

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