![](/img/trans.png)
[英]jQuery, search for element with value in attribute among the matched elements
[英]jQuery: How to calculate the maximal attribute value of all matched elements?
考慮以下 HTML:
<div class="a" x="6"></div>
<div class="a" x="9"></div>
<div class="a" x="2"></div>
...
<div class="a" x="8"></div>
您將如何找到所有.a
元素的最大x
值?
假設所有x
值都是正整數。
只需循環它們:
var maximum = null;
$('.a').each(function() {
var value = parseFloat($(this).attr('x'));
maximum = (value > maximum) ? value : maximum;
});
我得到了另一個版本:
var numbers = $(".a").map(function(){
return parseFloat(this.getAttribute('x')) || -Infinity;
}).toArray();
$("#max").html(Math.max.apply(Math, numbers));
這使用 map 函數來提取 x-Attributes 的值,將對象轉換為數組並將數組元素作為函數參數提供給Math.max
Math.max 技巧是從http://ejohn.org/blog/fast-javascript-maxmin/竊取的
更新
添加“|| -Infinity”以在不存在屬性時正確處理案例。 見@kubedan的小提琴
用現代 javascript 回到這個問題:
let maxA = $(".a").get().reduce(function (result, item) {
return Math.max(result, $(item).attr("x"));
}, 0);
您還可以在 jQuery 中使用 Array.sort,如此處所述,然后使用 $('.a:last') 獲取所選元素。
我正在做一些關於這個主題的測試,如果性能很重要,一個古老但簡單的for
會比jQuery.map()
, Math.apply()
和Array.sort()
更好:
var items = $(".a");
for (var i = 0; i < items.length; i++) {
var val = items.eq(i).prop('x');
if (val > max) max = val;
}
以下是jsperf測試: http : //jsperf.com/max-value-by-data-attribute 。 沒有什么特別激烈的,但無論如何都很有趣。
var max = null;
$('.a').each(function() {
var x = +($(this).attr('x'));
if (max === null || x > max)
max = x;
}
alert(max === null ? "No matching elements found" : "The maximum is " + max);
請注意將屬性轉換為數字的一元+
運算符。 您可能想要添加一些錯誤檢查以確保它實際上是一個數字 - 並且該屬性根本存在。 您可以將選擇器更改為僅選擇具有類和屬性的元素: $('.a[x]')
。
var max =0;
$('.a').each(function(){
if(parseFloat($(this).attr('x'))>max)
{
max = parseFloat($(this).attr('x')) ;
}
});
alert(max);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.