最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Which is better practice for adding a class using jQuery? - Stack Overflow

programmeradmin1浏览0评论
$("#" + parentElementId + " label").attr("class", "disabled")

VS

$('#radiolabel').addClass('disabled');

Which are the pros and cons?

Thanks

$("#" + parentElementId + " label").attr("class", "disabled")

VS

$('#radiolabel').addClass('disabled');

Which are the pros and cons?

Thanks

Share Improve this question edited Feb 1, 2012 at 21:37 weltraumpirat 22.6k5 gold badges43 silver badges54 bronze badges asked Feb 1, 2012 at 21:29 Ajax3.14Ajax3.14 1,6955 gold badges24 silver badges42 bronze badges
Add a ment  | 

4 Answers 4

Reset to default 13

The two are not the same. Using attr will replace the whole attribute. addClass will add the class to the existing classes.

As the name suggests addClass is made for this specific purpose, so I'd use that.

Here are some advantages of the two ways to do this:

addClass("disabled") Pros:

  1. If you have other classes on your object, addClass() will preserve those while adding a new class. I pretty much always want to preserve the ability to use other classes for CSS styling reasons or mon selector reasons so addClass() makes it possible to add the disabled class without disturbing other classes on the same object for other reasons.
  2. The code reads a little more self-explanatory since the name addClass() tells someone reading the code exactly what it's doing.
  3. addClass() automatically manages separators between class names so there is no extra accumulation of separators when you have multiple class names which can occur if you just get the current classname and add onto it yourself with string manipulation.

attr("class") = "disabled" Pros:

  1. If you only ever want one class name on the object, this one statement insures that you will have only one class name.
  2. A direct assignment of the one class can be faster than addClass() which has to examine what's there first and add a class to the pre-existing classes which jQuery does with a regex match. Max speed would actually be with element.className = "disabled" (no jQuery at all).

I'd go for addClass, it's easier to read, and if your editor supports code pletion, also faster to type.

You better go for the addClass() you will save time and writting, and gain more efficiency.

发布评论

评论列表(0)

  1. 暂无评论