Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
884 views
in Technique[技术] by (71.8m points)

performance - JQuery class selector vs id selector

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);
});

or

   $("#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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can use an ID filter without multiple selectors:

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

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.

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.

Which is better?

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.

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
...