简体   繁体   中英

Javascript for loop stuck on i = 2?

I am writing a javascript for loop and it keeps getting stuck on i = 2

 var i;
 for ( i = 0 ; i < $('ul#questions span').length + 1; i++){
  console.log("i",i)
  var id = document.getElementById(i);
  if(i = count){
    $( id ).show();
  }else{
    $( id ).hide();
  }
 }

在此处输入图像描述

replace i = count to i == count

 var i;
 for ( i = 0 ; i < $('ul#questions span').length + 1; i++){
  console.log("i",i)
  var id = document.getElementById(i);
  if(i == count){
    $( id ).show();
  }else{
    $( id ).hide();
  }
 }

Instead of performing a comparison, you are assigning i inside of the loop, preventing it from incrementing properly.

 var i; for ( i = 0; i < $('ul#questions span').length + 1; i++) { console.log("i",i) var id = document.getElementById(i); if (i == count) { // Comparison instead of assignment $( id ).show(); } else { $( id ).hide(); } }

if (i = count) means "if assignment of count to i succeeds do..."

To avoid that endless loop you should change it to if (i == count) to make your condition "if count is equal to i do..."

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