如何在jQuery中选择具有相同属性值的元素?

时间:2012-02-16 20:17:06

标签: jquery jquery-selectors

说我有这样的结构:

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

我希望隐藏除第一个之外具有相同属性的所有div,所以我得到:

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

现在我知道我可以这样做:

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

问题是,data-stuff的值是动态生成的并且是不可预测的。我该怎么做才能完成这项任务?

编辑

DOM元素本身不一定相同,因此$ .unique()在这里不会有用。同样重要的是FIRST仍然是显示的,因此重新排序不会发生。

4 个答案:

答案 0 :(得分:5)

蛮力方式:

var found = {};

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

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

答案 1 :(得分:4)

这样的事情怎么样:

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

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

答案 2 :(得分:2)

首先,rel不用于存储数据。根据W3C,rel描述了“从当前文档到href属性指定的锚点之间的关系。此属性的值是以空格分隔的链接类型列表。”

其次,rel只是<a><link>的属性。您真的想要使用data-* HTML5属性。不要担心浏览器支持,它一直可以回到IE 66(可能是5)。

这可以通过JQuery $.data('name')函数访问。

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

可通过以下方式访问:

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

答案 3 :(得分:0)

这意味着:如果你选择第一个元素,你想隐藏每个兄弟; 因此,使用JBrothersByAttr jquery插件,它是 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();

演示: http://jsfiddle.net/abdennour/7ypEa/1/

说明: 1.通过:eq(0)

选择第一个
   var jq= $('[data-stuff=foo]:eq(0)')

2.通过data-stuff选择具有相同JBrothersByAttr attr值的其他元素:

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

3.隐藏

brothers.hide()
相关问题