I have an element which I'd like to give a data attribute which contains a series of values, i.e., an Array
. Then I'd like to be able to select it based on any of the values in that series. Something like this:
<div id="example" data-my-series='["foo", "bar"]'></div>
Then I was hoping to select it based on the fact that it has "foo"
in it. I'm not really sure how I'd go about it, though. I know I'd do $('div[data-my-series="foo"]')
if I wasn't taking this approach, but, obviously that's not the case. Any suggestions?
Edit: Also, how can I achieve the inverse of this? i.e., select an element which does not have "foo"
in its data-my-series
?
I have an element which I'd like to give a data attribute which contains a series of values, i.e., an Array
. Then I'd like to be able to select it based on any of the values in that series. Something like this:
<div id="example" data-my-series='["foo", "bar"]'></div>
Then I was hoping to select it based on the fact that it has "foo"
in it. I'm not really sure how I'd go about it, though. I know I'd do $('div[data-my-series="foo"]')
if I wasn't taking this approach, but, obviously that's not the case. Any suggestions?
Edit: Also, how can I achieve the inverse of this? i.e., select an element which does not have "foo"
in its data-my-series
?
3 Answers
Reset to default 3$( "[data-my-series*='foo']" )
Here ya go!
The simplest way is very similar to what you are doing, just use the Attribute Contains Selector instead of the equals selector: $('div[data-my-series*="foo"]')
You can see more about it here: http://api.jquery./attribute-contains-selector/
Edit:
To answer the ment below, you can layer selectors in jQuery so take a look at the ":not()" selector. The usage would be $('div:not([data-my-series*="foo"])')
.
Make sure you don't put the div
inside the :not
. Also you will probably want to add [data-my-series]
outside the :not
as well to make sure you only select divs that have that data attribute.
Final product:
$('div[data-my-series]:not([data-my-series*="foo"])')
Watch out. The accepted answer will do substring matching and probably result in matches you didn't intend.
$('[data-my-series*="foo"]')
will not just find <div data-my-series="foo">
but will also include <div data-my-series="foobar">
in the results
You should use ~ instead of * to do whole-word matching $('[data-my-series~="foo"]')
. This will result in matching foo
but not foobar
If you want multiple words in the data string, use spaces to separate them: http://api.jquery./attribute-contains-word-selector/
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744090382a4556966.html
评论列表(0条)