Do you use quotes in jQuery when searching for att

2020-03-02 02:50发布

问题:

If I have a link like this:

<a data-btn="login"></a>

If I wished to select in jQuery using the data attribute which should I do?

var a = $("[data-btn='login']");  //This?

var a = $("[data-btn=login]");    //Or this?

回答1:

As of jQuery 1.5, both approaches will work, and function identically.

jQuery used to require quotes around attribute values, so your second selector won't work with previous versions. If you're stuck with an older version for some reason, use the first selector.



回答2:

Even in jQuery 1.5+ I still use quotes, as sometimes it doesn't work without them.



回答3:

Funny, I use this syntax:

var a = $('[data-btn="login"]');

which stems from my years in PHP where (and this could open a huge can of worms) using double quotes is arguably slower because it's open to interpreting variables within them whereas single quote strings are not - so I use single quotes more often than not.

I also use single quotes primarily in JavaScript because it's often mixed with HTML which, technically, should have all attribute values surrounded in double quotes, not single quotes and using single quotes saves me from having to escape quotes.