JQuery 'on' vs. 'live'

后端 未结 2 781
北海茫月
北海茫月 2020-12-18 08:51

I have a scenario where JQuery \'on\' & \'live\' do not perform the same. Perhaps someone can point out why. I am using JQuery 1.7.2 with my project and in this build,

相关标签:
2条回答
  • 2020-12-18 09:21

    That's the whole point of live(). It rebinds new DOM elements when they are created. There are a lot of similar questions on jQuery's site, like this one, because it can be a bit confusing.

    According to the jQuery docs, you use live() to:

    Attach an event handler for all elements which match the current selector, now and in the future.

    The "...in the future" part is key, because on() does not have that.

    0 讨论(0)
  • 2020-12-18 09:31

    One does not simply replace .live with .on.

    $("a.listajax").live('click', function(e))
    

    Is equivalent to:

    $(document).on('click', 'a.listajax', function(e))
    

    Important

    If there's a common ancestor for all your .listajax anchors that will not be removed from the DOM, you should use that (the deepest one possible) instead of document; this will improve performance.

    0 讨论(0)
提交回复
热议问题