有没有选择器参数和jquery委托的jquery有什么区别? [英] What is the difference between jquery on with / without selector parameter and jquery delegate?

查看:83
本文介绍了有没有选择器参数和jquery委托的jquery有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用jquery 1.10。我想知道这三个函数之间的区别。

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 delegate function?

$(".dropdown-menu").on("click", ".show_opt_menu", function() {
    alert("hello");
});
$(".dropdown-menu .show_opt_menu").on("click", function() {
    alert("hello");
});
$(".dropdown-menu").delegate(".show_opt_menu", "click", function() {
    alert("Delegate");
});

任何人都可以解释一下吗?

Can anybody explain me?

推荐答案

首先,第三个函数( .delegate )已被 .on (jQuery 1.7以上)所以我不会使用它。

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

第二种方法将运行复杂的选择器.dropdown-menu .show_opt_menu,这是(相对的) )昂贵的,因为它首先得到所有 .show_opt_menu s然后看看哪些父母是 .dropdown-menu 。然后它会为每个元素绑定一个事件。这是(相对)昂贵的,因为你正在运行一个慢查询,然后绑定可能很多事件。

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.

第一种方法是最好的,因为它只绑定一个事件到 .dropdown-menu 然后每当点击事件冒泡时,它会检查事件以查看原始目标是什么是。这是一个便宜得多的选择,因为只有一个事件受到约束,它的性能要高得多。

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.

摘要:# 1是最好的,#2通常已经完成,但更糟糕的是,#3已经过时了。

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.

这篇关于有没有选择器参数和jquery委托的jquery有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆