开发者

How can I use jquery to check if two attributes have the same value?

开发者 https://www.devze.com 2023-03-31 00:56 出处:网络
I\'m trying to write a jquery selector that will select objects that have the same value for two of their attributes.

I'm trying to write a jquery selector that will select objects that have the same value for two of their attributes.

Something like this:

$('div[attr1=attr2]')

Given:

<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>

I want it to return links to 开发者_开发技巧the B and D divs.

Any thoughts?


You can do this with custom selectors with arguments.

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

You define the custom selector like this:

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

For performance, add [attr1][attr2] to the selector so that the native DOM filters out nodes that don't have both attributes.


I think the attribute selector only allows you to compare with a constant value. But you can use the .filter() function to do the comparison:

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


Something like this would do the trick (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/>');
});

with the html something like:

<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>


If i get you right, you want to know if any attribute has the same value, regardless of its name. You could do it like this:

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
    }
})


use a double equals sign (==) to check for equality in an statement. single equals(=) is for assignment. So if($('div[attr1] == div[attr2]') { do something });

0

精彩评论

暂无评论...
验证码 换一张
取 消