简体   繁体   中英

Javascript loop stop using if condition

$("div").each(function(i, obj) {
  i++;
  var stopLoop = false; 
  if (!$(obj).attr('style') && stopLoop !== true) {
    $(obj).attr('style', 'background:'+getRandomColor()+';');
    return false;
  }
});

Above method work, it will add one new color to my div whenever the function got fired. But because of the return false is used, my code after it will not run. So I try to use if condition instead of return false, it doesn't work the same.

// doesn't work

    $("div").each(function(i, obj) {
      i++;
      var stopLoop = false; 
      if (!$(obj).attr('style') && stopLoop !== true) {
        $(obj).attr('style', 'background:'+getRandomColor()+';');
        stopLoop = true;
      }
    });

Try with break :

$("div").each(function(i, obj) {
    i++;
    if (!$(obj).attr('style')) {
        $(obj).attr('style', 'background:'+getRandomColor()+';');
        break;
    }
});

Use the solution below

var stopLoop = false;

$("div").each(function(i, obj) {
  if(i === 0) {
    stopLoop = false;
  }

  i++;

  if (!$(obj).attr('style') && !stopLoop) {
    $(obj).attr('style', 'background:'+getRandomColor()+';');
    stopLoop = true;
  }
});

declare stopLoop variable in global scope. in you case stopLoop is deaclared inside function and after function ends it's work variable will be deleted. and on the other iteration it will be declared again with value false

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