2011-08-25 68 views
4

我想写一个jQuery选择器,将选择具有相同的值为他们的两个属性的对象。如何使用jquery检查两个属性是否具有相同的值?

事情是这样的:

$('div[attr1=attr2]') 

考虑:

<div attr1="foo" attr2="bar">A</div> 
<div attr1="bar" attr2="bar">B</div> 
<div attr1="foo" attr2="bar">C</div> 
<div attr1="foo" attr2="foo">D</div> 

我想它返回链接到B和d的div。

有什么想法?

回答

7

你可以用custom selectors with arguments做到这一点。

$('div:attrEqual(attr1 attr2)') 

您定义自定义选择这样的:

$.expr[':'].attrEqual = function(obj, index, meta, stack) { 
    var attrs = meta[3].split(" "); 
    return $(obj).attr(attrs[1]) == $(obj).attr(attrs[0]); 
}; 

对于性能,增加[attr1][attr2]的选择,使本机DOM过滤掉不具有两个属性节点。

+0

我认为这正是他想要的。 –

+0

非常性感。我完全明白了:这是否会工作,无论attr的名称是什么? – meo

+0

但它什么也没有返回:http://jsfiddle.net/EGMw2/2/ – meo

0

使用双等号(==)来检查语句中的相等性。单个等于(=)用于分配。所以如果($('div [attr1] == div [attr2]'){do something});

+0

属性等于在jQuery选择只使用一个等号。请参阅http://api.jquery.com/attribute-equals-selector/ –

+0

是的,选择器使用一个等号,但问题似乎表明它正在寻找多个属性值之间的平等检查。也许我误解了文档,但看起来单个等于是用来关联属性和它的值,而不是两个值之间的相等性检查。 – Evan

4

我认为属性选择器只允许你比较一个常量值。但是你可以使用.filter()功能做比较:

$('div[attr1][attr2]').filter(function(index) { 
    return $(this).attr('attr1') == $(this).attr('attr2'); 
}) 
+0

你需要删除你的示例中的前导'$('''以使其工作。 – meo

+0

谢谢,我编辑了我的答案。 –

1

像这样的事情会做的伎俩(The Fiddle):

function GetWithSameAttributes (parID) 
{ 
    var output = new Array(); 

    $('#'+parID).children().each(function() 
    { 
     if ($(this).is('[attr1="'+$(this).attr('attr2')+'"]')) 
      output.push($(this).html()); 
    }); 
    return output; 
} 

$(function() 
{ 
    for (val in GetWithSameAttributes('Items')) 
     document.writeln(val + ' has the same attributes<BR/>'); 
}); 

与HTML类似:

<div id="Items"> 
    <div attr1="foo" attr2="bar">A</div> 
    <div attr1="bar" attr2="bar">B</div> 
    <div attr1="foo" attr2="bar">C</div> 
    <div attr1="foo" attr2="foo">D</div> 
</div> 
1

如果我得到你的权利,你想知道的任何属性具有相同的价值,不管它的名字。你可以做这样的:

http://jsfiddle.net/zuwZh/2/

$("div").filter(function(){ 
var attributes = this.attributes, 
    i = attributes.length, 
    attrValues = [], 
    $that = $(this); 
    if(i !== 1) { 
    while(i--) { 
     var attr = attributes[i]; 
     attrValues.push(attr.value); 
    } 
    attrValues = attrValues.sort(); 
    if(attrValues[0] === attrValues[1]) { 
     return $that; //only checks between two attributes, but you could extend that 
    } 
}) 
相关问题