问题
If my markup looks like this:
<div data-test="{ "value" : "bar", "_id" : 1234, "name" : "john", "age" : 25 }">...</div>
<div data-test="{ "value" : "foo", "_id" : 1235, "name" : "paul", "age" : 26 }">...</div>
<div data-test="{ "value" : "drummer", "_id" : 1236, "name" : "ringo", "age" : 22 }">...</div>
How would I select a particular element using JQuery if I only had the key 'bar' or 'foo'?
I could pull out the whole object for each row and iterate through it looking for a match but I'd rather not if there is a more efficient method.
How can I cleanly select based on the property of an object?
回答1:
You can use:
$("div").filter(function() {
return $(this).data("test").value == "bar";
})
jQuery.data()
automatically parses a data value that's in JSON format into the corresponding object.
FIDDLE
回答2:
Try this
$('div[data-test$=": bar }"]')
$('div[data-test$=": foo }"]')
More details here
UPDATE:
If attributes are not ending with bar/foo then you could try contains selector
$('div[data-test*="'value' : 'bar'"]')
$('div[data-test*="'value': 'foo'"]')
More details here
Or you could also use starts selector if it starts with value
来源:https://stackoverflow.com/questions/12950554/how-to-select-an-element-based-on-the-property-of-an-object-inside-a-data-attrib