dynamically bind .on() method with event-map

狂风中的少年 提交于 2019-12-24 04:48:27

问题


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.



来源:https://stackoverflow.com/questions/13810137/dynamically-bind-on-method-with-event-map

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!