What is the difference between jquery on with / without selector parameter and jquery delegate?

前端 未结 4 1767
孤街浪徒
孤街浪徒 2021-01-18 06:38

I am using jquery 1.10. I want to know what the difference is between these three functions.

Which function is better and why?

What is the purpose of the del

4条回答
  •  悲&欢浪女
    2021-01-18 07:29

    First off, the third function (.delegate) has been superseded by .on (jQuery 1.7 onwards) so I wouldn't use that.

    The second method will run the complex selector ".dropdown-menu .show_opt_menu", which is (relatively) expensive as it first gets all .show_opt_menus then looks to see which have parents that are .dropdown-menu. It then binds one event per element. This is (relatively) expensive since you're running a slow query, then binding potentially many events.

    The first method is the best, as it binds only one event to .dropdown-menu then whenever a click event bubbles up to it, it checks the event to see what the original target was. This is a much cheaper option, and since there's only one event being bound it's a lot more performant.


    Summary: #1 is the best, #2 is commonly done but worse, #3 is outdated.

    You likely won't notice any performance difference anyway, but it's worth paying attention to anyway because it's good practice. At some point, you may need to concern yourself with performance.

提交回复
热议问题