HTML:
<span personname="Mr. Bean" class="person person-male"></span>
<span personname="Neo" class="person person-male"></span>
<span personname="Neo" class="person person-male"></span>
<span personname="Trinity" class="person person-female"></span>
<span personname="Trinity" class="person person-female"></span>
<span personname="Neo" class="person person-male"></span>
<span personname="Mr. Bean" class="person person-male"></span>
JS:
Array.prototype.unique =
function () {
var a = [];
var l = this.length;
for (var i = 0; i < l; i++) {
for (var j = i + 1; j < l; j++) {
// If this[i] is found later in the array
if (this[i] === this[j])
j = ++i;
}
a.push(this[i]);
}
return a;
};
function unique(list) {
var result = [];
$.each(list, function (i, e) {
if ($.inArray(e, result) == -1) result.push(e);
});
return result;
}
$.unique($('span.person').get()).length // ==> 7
$.unique($('span.person')).length // ==> 7
$('span.person').get().unique().length // ==> 7
unique($('span.person').get()).length // ==> 7
unique($('span.person')).length // ==> 7
如何只获取唯一的DOM元素?
即$('span.person).unique().length // ==> 3
我正在寻找一个内置函数,如果有的话。
答案 0 :(得分:2)
如果您只想尝试获得唯一personname
,那么这将有效:
function uniquePerson(elements) {
var results = $();
var names = {};
elements.each(function() {
var name = (this).attr('personname');
if (!names[name]) {
results = results.add(this);
names[name] = true;
}
});
return results;
}
所有DOM元素都不同 - 您只想比较personname
属性,而不是整个元素。