Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

html - How to select elements with jQuery that have a certain value in a data attribute array

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.

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

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>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...