How to select elements with the same attribute value in jQuery?

孤街醉人 提交于 2019-12-23 09:34:49

问题


Say I have a structure like so:

<div data-stuff="foo"></div>
<div data-stuff="foo"></div>
<div data-stuff="foo"></div>
<div data-stuff="bar"></div>
<div data-stuff="bar"></div>
<div data-stuff="bar"></div>
<div data-stuff="baz"></div>

And I want to hide all the divs with the same attribute except the first, so I'd get:

<div data-stuff="foo"></div>
<div data-stuff="bar"></div>
<div data-stuff="baz"></div>

Now I know I could just do this:

$('[data-stuff=foo]:gt(0), [data-stuff=bar]:gt(0), [data-stuff=baz]:gt(0)').hide();

The problem is, the value of data-stuff is dynamically generated and is unpredictable. What could I do to accomplish this task?

EDIT

The DOM elements themselves aren't necessarily the same, so $.unique() won't help here. It's also important that the FIRST is the one that remains showing, so reordering can't happen.


回答1:


The brute force way:

var found = {};

$("[rel]").each(function(){
    var $this = $(this);
    var rel = $this.attr("rel");

    if(found[rel]){
        $this.hide();
    }else{
        found[rel] = true;
    }
});



回答2:


How about something like this:

$('div[rel]:visible').each(function(){
    var rel = $(this).attr('rel');
    $(this).nextAll('div[rel="'+rel+'"]').hide();
});

DEMO: http://jsfiddle.net/CsTQT/




回答3:


Firstly, rel is not used for storing data. According to the W3C, rel describes "the relationship from the current document to the anchor specified by the href attribute. The value of this attribute is a space-separated list of link types."

Secondly, rel is only an attribute on <a> and <link>. You really want to be using the data-* HTML5 attribute. Don't worry about browser support, it works all the way back to IE 66 (probably 5).

This will be accessable via the JQuery $.data('name') function.

<div data-foo="bar"></div>

will be accessable via:

$('div').filter(function(inputs){
    return $(this).data('foo') === 'bar';
}).hide()



回答4:


That is means : if you select the first element , you want to hide each brothers ; So use JBrothersByAttr jquery plugin which is a part of Mounawa3et منوعات Jquery plugin:

$('[data-stuff=foo]:eq(0)').brothersByAttr('data-stuff').hide();
$('[data-stuff=bar]:eq(0)').brothersByAttr('data-stuff').hide();
$('[data-stuff=baz]:eq(0)').brothersByAttr('data-stuff').hide();

Demo : http://jsfiddle.net/abdennour/7ypEa/1/

Explanation : 1. select the first via :eq(0)

   var jq= $('[data-stuff=foo]:eq(0)')

2.select the others elements that have the same value of data-stuff attr via JBrothersByAttr :

   var brothers=jq.brothersByAttr('data-stuff')

3.Hide it

brothers.hide()


来源:https://stackoverflow.com/questions/9318427/how-to-select-elements-with-the-same-attribute-value-in-jquery

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!