JQuery class selector vs id selector

后端 未结 5 622
天涯浪人
天涯浪人 2020-12-16 17:31

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(\"c         


        
5条回答
  •  一整个雨季
    2020-12-16 17:50

    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.

提交回复
热议问题