我们如何检查jQuery.each()
循环的最后一次迭代?我的循环正在对来自$.ajax
请求的对象进行迭代。
jQuery.ajax({
url: "<?php echo $this->getUrl('xs4arabia/index/getFetchrOrderLogs/'); ?>",
type: "GET",
data: {
tracking_id: tracking_id
},
dataType: "json",
success: function(data) {
jQuery.each(data, function(key, value) {
console.log(value);
})
}
});
传递给each()
处理函数的第一个参数是数组中当前元素的索引(尽管您当前已将其命名为key
)。您可以将其与数组的长度进行比较以找出当前位置:
$.each(data, function(index, value) {
var isLastElement = index == data.length -1;
if (isLastElement) {
console.log('last item')
}
console.log(value);
},
每个函数的第一个参数等于索引。
因此,您可以将索引与数据长度进行比较。
使用div标签查看此示例:
$(document).ready(function(){
var len = $('div').length;
$('div').each(function(index){
if (index === (len - 1))
alert('Last index');
});
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<div>1</div>
<div>2</div>
<div>3</div>
这是另一个使用包含数组属性的对象的示例:
var data = {
myArray:[1,2,3]
}
$(document).ready(function(){
var len = data.myArray.length;
$.each(data.myArray,function(index,value){
if (index === (len - 1))
alert(index);
});
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
您可以检查数据的长度并将其与键进行比较(请注意,第一个键为0)
jQuery.ajax({
url: "<?php echo $this->getUrl('xs4arabia/index/getFetchrOrderLogs/'); ?>",
type: "GET",
data: {tracking_id: tracking_id},
dataType: "json",
success: function (data) {
var arrLength = data.length;
jQuery.each(data, function (key, value) {
if( key == arrLength - 1 ) {
/* this is the last one */
}
console.log(value);
},
})
每个都传递给您的功能键和值。根据数据长度检查键(索引)。
if (key == data.length- 1) {
console.log('Last field');
}
虽然其他答案都是正确的,但我个人最喜欢这种方法,只需编写您自己的计数器即可:
var counter = 0;
$(yourselector).each(function(index,element){
counter++;
if( counter == $(yourselector).length )
{
// Last Element
}
else
{
// Not last Element
}
});