jQuery类选择器与ID选择器 [英] JQuery class selector vs id selector

查看:131
本文介绍了jQuery类选择器与ID选择器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有 7个不同的按钮,在单击时均执行相同的javascript功能.我应该使用类选择器还是ID选择器.

I have 7 different buttons that all perform the same javascript function on click. should i use class selector or id selector.

$("input.printing").on("click", function(event) {
     printPdf(event);
});

   $("#package1Pdf").click(function(event) {
         printPdf(event);
   });
$("#package2Pdf").click(function(event) {
         printPdf(event);
   });
$("#package3Pdf").click(function(event) {
         printPdf(event);
   });
$("#package4Pdf").click(function(event) {
         printPdf(event);
   });

每种技术都有哪些优缺点?这是更优选的.

What are the advantage and disadvantage of each? Which is more preferred.

推荐答案

您可以使用没有多个选择器的ID过滤器:

You can use an ID filter without multiple selectors:

$('[id^="package"]').click(printPdf);

上面将选择所有以"package"开头的ID.这意味着差异主要是语义上的.您应该选择对您的应用程序及其开发方式最有意义的内容.

The above will select all id's starting with "package". This means the difference is mostly semantic. You should choose that which is most meaningful to your application and the way it was developed.

请参见 jQuery属性选择器页面,以了解jQuery选择.在此页面上保留书签将使您不必再像第二个示例那样编写代码.

See the jQuery attribute selectors page to learn about the flexibility of jQuery selection. Keeping a bookmark on this page will prevent you from ever having to write code like your second example again.

哪个更好?

如果您设置了结构,从而拥有一个可以在逻辑上正确定义适当的元素集的类,则应使用该类进行选择.

If you have your structure set up so that you have a class that logically and correctly defines the appropriate set of elements, then that is what you should use to select on.

同样,如果您改为给元素指定了特别命名的ID,并且没有附加表示您要选择的描述性类名,请使用ID选择. 几乎所有应用程序(包括您自己的应用程序)都不会担心性能差异.

Likewise, if you have instead given elements specially named IDs and do not have a descriptive class name attached that represents what you want to select, then use the ID selection. The performance difference will be of no concern to almost any application, yours included.

这篇关于jQuery类选择器与ID选择器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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