2017-03-18 12 views
3

我有不同的數據屬性值的多個劃分,同一類 也需要使用jquery獲取值的數據值。例如我有數據值組2,3,5 以獲得所需的結果是組使用jquery的數據屬性的最大值

<div data-value="2" class="maindiv">test</div> 
<div data-value="5" class="maindiv">test</div> 
<div data-value="3" class="maindiv">test</div> 
etc. 

回答

0

你應該嘗試以下代碼中的5個。

function MaxId(selector) { 
    var max=null; 
    $(selector).each(function() { 
     var id = parseInt(this.id, 10); 
     if (isNaN(id)) { return; } 
     if ((max===null) || (id > max)) { max = id; } 
    }); 
    return [max]; 
} 
alert(MaxId('div.maindiv')); 

或者你也可以嘗試如下。

Math.max(one, two, three); 
1

你可以嘗試$.each()方法,如下圖所示:

var result = 0; 

$('.maindiv').each(function(index) { 
    if ($(this).data('value') > result) { 
     result = $(this).data('value'); 
    } 
}); 
// result now contains the max value, so do what you want with it 
console.log(result); 
1

沒有直接的方式,但這樣會做

var dataList = $(".maindiv").map(function() { 
    return parseInt($(this).attr("data-value")); 
}).get(); 
console.log(Math.max.apply(null, dataList)); 

https://jsfiddle.net/pgbf3o9f/