如何在jQuery中选择具有相同属性值的元素? [英] How to select elements with the same attribute value in jQuery?
本文介绍了如何在jQuery中选择具有相同属性值的元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
假设我有这样的结构:
<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,所以我得到:
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?
编辑
DOM元素本身不一定相同,所以$ .unique()在这里不会有用。同样重要的是FIRST是一个仍然显示的,所以重新排序不会发生。
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.
推荐答案
蛮力方式:
var found = {};
$("[rel]").each(function(){
var $this = $(this);
var rel = $this.attr("rel");
if(found[rel]){
$this.hide();
}else{
found[rel] = true;
}
});
这篇关于如何在jQuery中选择具有相同属性值的元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文