Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

jquery - 通过数据属性选择元素(Selecting element by data attribute)

Is there an easy and straight-forward method to select elements based on their data attribute?

(是否有一种简单而直接的方法来根据其data属性选择元素?)

For example, select all anchors that has data attribute named customerID which has value of 22 .

(例如,选择所有具有名为customerID数据属性,其值为22锚。)

I am kind of hesitant to use rel or other attributes to store such information, but I find it much harder to select an element based on what data is stored in it.

(我有点犹豫使用rel或其他属性来存储此类信息,但是我发现很难根据其中存储的数据来选择元素。)

  ask by Hazem Salama translate from so

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

1 Answer

0 votes
by (71.8m points)
$('*[data-customerID="22"]');

You should be able to omit the * , but if I recall correctly, depending on which jQuery version you're using, this might give faulty results.

(您应该可以省略* ,但是如果我没记错的话,根据您使用的jQuery版本,这可能会导致错误的结果。)

Note that for compatibility with the Selectors API ( document.querySelector{,all} ), the quotes around the attribute value ( 22 ) may not be omitted in this case .

(请注意,为了与Selectors API( document.querySelector{,all} )兼容, 在这种情况下,可能会省略属性值( 22 )周围的引号。)

Also, if you work with data attributes a lot in your jQuery scripts, you might want to consider using the HTML5 custom data attributes plugin .

(另外,如果您在jQuery脚本中大量使用数据属性,则可能需要考虑使用HTML5自定义数据属性插件 。)

This allows you to write even more readable code by using .dataAttr('foo') , and results in a smaller file size after minification (compared to using .attr('data-foo') ).

(这使您可以通过使用.dataAttr('foo')编写更具可读性的代码,并在缩小后产生更小的文件大小(与使用.attr('data-foo') )。)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...