简体   繁体   中英

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

I have an each loop with jquery (I wouldn't mind using a for loop if the code works better) and it's cycling through all divs with the class="searchMe". I would like to store the current div in a variable that I can use in the next iteration of the loop to compare a value with the new current div. Some code is removed (all working) to simplify things, but here's my code:

$('.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
});

Everything is working properly except the last 3 lines. is this possible with an each/for loop?

you can use index in $.each()

like

$('.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));
   }
});

Or Alternatively you can define lastid like

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
});

Read eq() and $.each()

I don't know why sort up is needed when you are comparing backwards alone. you can replace the last three lines with...

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM