How to select an element based on the property of an object inside a data attribute?

微笑、不失礼 提交于 2021-02-08 05:22:22

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!