简体   繁体   English

jQuery按属性值获取/选择元素

[英]jQuery get/select element by property value

Is there a way to get/select an element by it's property value, just as it is possible with the attribute values: 有没有办法通过它的属性值来获取/选择元素,就像使用属性值一样:

$('[attribute="value"]')

For example, I'd set a property using jQuery like this: 例如,我使用jQuery设置一个属性,如下所示:

$('#foo').prop('my-property', 'value');

and then I'd like to find an element which has property 'my-property' and it has value 'value' . 然后我想找到一个具有属性'my-property'并且它具有值'value'的元素。

No, there isn't anything exposed at the selector level that can select by property value, just (as you know) attribute value. 不,选择器级别没有任何可以通过属性值选择的内容,只是(如您所知)属性值。

Some properties are reflections of attributes, which means that setting the property sets the attribute, which allows you to use attribute selectors. 某些属性是属性的反射,这意味着设置属性会设置属性,从而允许您使用属性选择器。 For instance, an input element's defaultValue property is a reflection of its value attribute (which its value property is not). 例如, input元素的defaultValue属性是其value属性的反映(其value属性不是)。

Otherwise, you select by what you can and use filter to filter the resulting list to only the elements you actually want. 否则,您可以根据需要进行选择,并使用filter器将结果列表过滤为仅实际需要的元素。

Re your edit: 重新编辑:

For example, I'd set a property using jQuery like this: 例如,我使用jQuery设置一个属性,如下所示:

 $('#foo').prop('my-property', 'value'); 

No, there's no way to select by that property directly, you'd need something like my filter suggestion above: 不,没有办法直接选择该属性,你需要像我上面的filter建议:

var list = $("something-that-gets-you-close").filter(function() {
    return this["my-property"] == "value";
});

You might consider using data-* attributes instead: 您可以考虑使用data-*属性:

$("#foo").attr("data-my-property", "value");

then 然后

var list = $("[data-my-property='value']");

to select it (the inner quotes are optional for values matching the definition of a CSS identifier ). 选择它(内部引号对于匹配CSS标识符定义的值是可选的)。 Note that attribute values are always strings. 请注意,属性值始终是字符串。

Beware: There's a persistent misconception that jQuery's data function is a simple accessor for data-* attributes. 注意:有一种持续的误解,即jQuery的data函数是data-*属性的简单访问器。 It is not. 它不是。 It manages a data cache associated with the element by jQuery, which is initialized from data-* attributes but disconnected from them. 它通过jQuery管理与元素关联的数据缓存,它从data-*属性初始化但与它们断开连接。 In particular, .data("my-property", "value") would not let you find that later via a [data-my-property=value] selector. 特别是, .data("my-property", "value")不允许您稍后通过[data-my-property=value]选择器找到它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM