对于Loop/Each Loop变量存储和比较(jQuery或Javascript

For Loop/Each Loop variable storage and comparison (jQuery or Javascript

本文关键字:Loop jQuery Javascript 比较 存储 Each 变量 对于      更新时间:2023-09-26

我有一个带有jquery的each循环(如果代码运行得更好,我不介意使用for循环),它使用class="searchMe"在所有div中循环。我想把当前div存储在一个变量中,我可以在循环的下一次迭代中使用这个变量来比较一个值和新的当前div。为了简化事情,删除了一些代码(全部有效),但下面是我的代码:

$('.searchMe').each(function(){
  var id = $(this);
  sortUp += 1,
  sortDown -= 1;
  if (test) {
    id.attr("name", ""+sortUp+"");
  }
  else {
    id.attr("name", ""+sortDown+"");
  }
  if ( id.attr("name") > lastId.attr("name") ) {
    id.insertBefore(lastId);
  }
  lastId = id; //this doesn't work, but illustrates what I'm trying to do
});

除了最后3行外,一切都正常。通过each/for循环,这可能吗?

我不知道当您单独进行向后比较时,为什么需要进行排序。你可以将最后三行替换为。。。

if ( parseInt(id.attr("name")) > parseInt(id.prev().attr("name")) ) {
 id.insertBefore(id.prev()).remove();
}

您可以在$.each() 中使用index

$('.searchMe').each(function(index){
   var id = $(this);
   sortUp += 1,
   sortDown -= 1;
   if (test) {// don't know what is test, let it is predefined
     id.attr("name", sortUp);// no need to add ""
   }
   else {
     id.attr("name", sortDown);
   }
   if ($('.searchMe').eq(index-1).length && id.attr("name") > $('.searchMe').eq(index-1).attr("name") ) {
     id.insertBefore($('.searchMe').eq(index-1));
   }
});

或者或者您可以像一样使用define lastid

var lastId='';// let it be global
$('.searchMe').each(function(index){
   var id = $(this);
   sortUp += 1,
   sortDown -= 1;
   if (test) {// don't know what is test, let it is predefined
      id.attr("name", sortUp);// no need to add ""
   }
   else {
      id.attr("name", sortDown);
   }
   if (id.attr("name") > lastId.attr("name") ) {
      id.insertBefore(lastId);
   }
   lastId=id;// assign here the current id
});

读取eq()和$.each()