dynamically bind .on() method with event-map

2019-07-17 19:12发布

问题:

I'm using this syntax to make sure that the events bind on dynamically added li elements

$('ul.list').on('click', 'li', function() {

   //do something

});

I tried to archive the same with an event-map like this:

$('ul.list').hammer({
    css_hacks : false
}).on({
     swipe : function(event){
        //do something
     },
     doubletap : function(event){
        //some more code
     }
}, 'li');

but its not working at all. If I bind the events directly to the li element it works fine for existing elements, but not for dynamically added elements.

$('ul.list').find('li').hammer({
    css_hacks : false
}).on({
     swipe : function(event){
        //do something
     },
     doubletap : function(event){
        //some more code
     }
});

How to bind the event-map to future elements?

回答1:

on() with 2 parameters is eqvivalent to the old bind() functionality.

If you want to make it work like live() did, pass a third argument like in your first example.

Also, if your'e having trouble when chaining functions on the hammer() method, inspect it and make sure that it returns "this".

$('ul.list').on({
    swipe : function() { ... },
    doubletap : function() { ... }
},'li');


回答2:

if you look into jquery document,jquery live

it says,Chaining methods is not supported. For example, $("a").find(".offsite, .external").live( ... ); is not valid and does not work as expected.

so you can do this:

$('ul.list > li').hammer({
    css_hacks : false
}).live({
     swipe : function(event){
        //do something
     },
     doubletap : function(event){
        //some more code
     }
});

but it's deprecated, I think your first example should work.

I tried this:

<ul>
<li>aaa</li>
<li>bbb</li>
</ul>

and

$("ul").on({
    click:function(){
        $(this).html('clicked');
        },
    dblclick:function(){
        $(this).html('double clicked');
        }
    },'li');

it works, so i guess your problem may be the name of event.