我有一个div列表,每个div都有数据ID号。
<div id="divblocks">
<div data-id="200"></div>
<div data-id="210"></div>
<div data-id="170"></div>
<div data-id="230"></div>
</div>
如何从连续的DIV中获取最大的ID号?
类似这样的东西:
maxid = jQuery('#divblocks').find("div").max().data("id");
答案 0 :(得分:0)
遍历div并成对比较ID:
var highest_id = 0;
var id;
$('#divblocks > div').each(function(i,e){
id = $(e).data('id');
if(highest_id < id){
highest_id = id;
}
});
alert(highest_id);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="divblocks">
<div data-id="200"></div>
<div data-id="210"></div>
<div data-id="170"></div>
<div data-id="230"></div>
</div>
答案 1 :(得分:0)
我的长版:
const $divs = $('#divblocks div')
// parsing nodeList to arrayList
const arrayDivs = Array.from($divs)
// getting array ids values
const arrayDataIds = arrayDivs.reduce((acc, item) => {
acc.push($(item).data('id'))
return acc
}, [])
// getting max value of ids
const largestId = Math.max.apply(null, arrayDataIds)
console.log(largestId)
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="divblocks">
<div data-id="200"></div>
<div data-id="210"></div>
<div data-id="170"></div>
<div data-id="230"></div>
</div>
小版本:
const $divs = $('#divblocks div')
const largestId = Math.max.apply(null, Array.from($divs).reduce((acc, item) => {
acc.push($(item).data('id'))
return acc
}, []))
console.log(largestId)
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="divblocks">
<div data-id="200"></div>
<div data-id="210"></div>
<div data-id="170"></div>
<div data-id="230"></div>
</div>
定位div:
$(`div [data-id="${largestId}"]`)