jQuery 按属性值过滤

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4547363/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 17:26:59  来源:igfitidea点击:

jQuery filter by an attribute value

jqueryattributesfilter

提问by Mark

<div class="selectedColumns" >
<a href="#" attributeid="19" >Driver License State</a>
<a href="#" attributeid="21" >Email</a>
<a href="#" attributeid="23" >Experience Level</a>
<a href="#" attributeid="26" >First Name</a>
<a href="#" attributeid="71" >Is Account Enabled</a>
<a href="#" attributeid="39" >Last Contacted Date</a>
<a href="#" attributeid="40" >Last Name</a>
<a href="#" attributeid="41" >Middle Name</a>
<a href="#" attributeid="6">Carrier</a>
</div>

I have a collection of links. Each link has an attributeid property. I would like to filter by attribute value. So in the links above if I have a value of 41 it would return the Middle Name link.

我有一个链接集合。每个链接都有一个 attributeid 属性。我想按属性值过滤。因此,在上面的链接中,如果我的值为 41,它将返回中间名链接。

var link = $('.selectedColumns a:[attributeid==' + $(this).val() + ']');

This did not work?

这不起作用?

回答by Jeff Lowery

Not claiming this is any more elegant, but using filter() on a collection allows much more flexibility on what you can match on, and is a little less error prone than string concatenation.

并不是说这更优雅,但是在集合上使用 filter() 可以让您在匹配的内容上具有更大的灵活性,并且比字符串连接更不容易出错。

var matching = $('.selectedColumns a').filter(function(){
                   return $(this).attr('attributeid') == 41
                });
    matching.prop('selected', true);

回答by Tjirp

use a single = instead of 2. Also, the : shoudn't be there afaik

使用单个 = 而不是 2。此外, : 不应该在那里 afaik

var link = $('.selectedColumns a[attributeid=' + $(this).val() + ']');

回答by Nick Craver

There's no need for the :or double =in your attribute-equals selector, it should just be:

您的attribute-equals 选择器中不需要 the :or double ,它应该是:=

$('.selectedColumns a[attributeid=' + $(this).val() + ']');

Also if you're using invalid attributes, consider using data-attributeswhich arevalid in HTML5, for example data-idinstead of attributeid.

此外,如果你正在使用无效的属性,可以考虑使用data-属性,有效的HTML5,例如data-id代替attributeid