jQuery按属性值过滤

Mar*_*ark 21 jquery attributes filter

<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>
Run Code Online (Sandbox Code Playgroud)

我有一系列链接.每个链接都有一个attributeid属性.我想按属性值过滤.所以在上面的链接中如果我的值为41,它将返回中间名链接.

var link = $('.selectedColumns a:[attributeid==' + $(this).val() + ']');
Run Code Online (Sandbox Code Playgroud)

这没用?

Jef*_*ery 34

不要声称这更优雅,但在集合上使用filter()可以更灵活地匹配,并且比字符串连接更不容易出错.

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


Tji*_*irp 22

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

var link = $('.selectedColumns a[attributeid=' + $(this).val() + ']');
Run Code Online (Sandbox Code Playgroud)


Nic*_*ver 19

属性等于选择器中不需要:或者double ,它应该只是:=

$('.selectedColumns a[attributeid=' + $(this).val() + ']');
Run Code Online (Sandbox Code Playgroud)

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