如何选择jQuery中在数据属性数组中具有特定值的元素 [英] How to select elements with jQuery that have a certain value in a data attribute array
问题描述
在jQuery中有没有一种方法可以选择在数据属性数组中具有特定值的元素?
请考虑html代码片段:
< li id =person1data-city =Boston,New York,San Fransisco>
人名1
< / li>
人名2
< / li>
在jQuery中选择数据城市中所有具有纽约的人的最佳方式是什么属性?
解决方案应该考虑到某些城市名称出现在其他城市名称中(例如2:伦敦,新伦敦)
示例2:
< li id =person1data-city =Boston,London,圣弗朗西斯科>
人名1
< / li>
人名2
< / li>
在jQuery中选择data-city属性中所有具有London的人的最佳方式是什么?不应该选择新伦敦的城市。 可以使用选择器 attr * = string]
其中 * =
匹配标签值中任何位置的字符串。我已将文本着色为红色,以便您可以测试...
$(li [data-city * = New纽约])的CSS({颜色: '红'});
或者通过更复杂的方法来适应示例二的需求:
$(li)
.filter(function(){
return $(this).attr('data-city') .match(/(^ |,\s +)London(,| $)/)
})
.css({color:'red'});
此方法使用过滤器遍历所选的 li
并匹配属性 data-city
的所有元素匹配正则表达式(^ |,\ s +)伦敦(,| $)
这意味着...
- 开始或逗号(
^ |,$ c
- 和一个或多个空格(
\ s +
)
- 通过
伦敦
- 后跟逗号或结尾(
,| $
)
- 和一个或多个空格(
我使用这个HTML:
< li id =person1data-city =Boston,New York,San Fransisco,London>
人名1
< / li>
人名2
< / li>
人名3
< / li>
is there a way in jQuery to select elements that have a certain value in a data attribute array?
Consider this snippet of html:
<li id="person1" data-city="Boston, New York, San Fransisco">
Person name 1
</li>
<li id="person2" data-city="Los Angeles, New York, Washington">
Person name 2
</li>
What is the best way in jQuery to select all persons with "New York" in the data-city attribute?
The solution should take in account that certain citynames appear in other city names (in example 2: London, New London)
Example 2:
<li id="person1" data-city="Boston, London, San Fransisco">
Person name 1
</li>
<li id="person2" data-city="Los Angeles, Washington, New London">
Person name 2
</li>
What is the best way in jQuery to select all persons with "London" in the data-city attribute? A city with "New London" should not be selected.
You can use the selector tag[attr*=string]
where *=
matches the string found anywhere in the tag value. I have colored the text red, just so you can test...
$("li[data-city*=New York]").css({color:'red'});
Or via more complex method to fit needs of example two:
$("li")
.filter( function(){
return $(this).attr('data-city').match(/(^|,\s+)London(,|$)/)
})
.css({color:'red'});
This method uses filter to go through the list of selected li
and match all elements with attribute data-city
that matches regex (^|,\s+)London(,|$)
which means...
- start or comma (
^|,
) - and one or more spaces (
\s+
) - followed by
London
- followed by comma or end (
,|$
)
I used this HTML:
<li id="person1" data-city="Boston, New York, San Fransisco, London">
Person name 1
</li>
<li id="person2" data-city="Boston, New Jersey, London, San Fransisco">
Person name 2
</li>
<li id="person3" data-city="Los Angeles, New York, New London, Washington">
Person name 3
</li>
这篇关于如何选择jQuery中在数据属性数组中具有特定值的元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!