Do you use quotes in jQuery when searching for att

2020-03-02 02:18发布

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?

3条回答
混吃等死
2楼-- · 2020-03-02 02:41

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.

查看更多
兄弟一词,经得起流年.
3楼-- · 2020-03-02 02:52

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

查看更多
一纸荒年 Trace。
4楼-- · 2020-03-02 02:53

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.

查看更多
登录 后发表回答