JavaScript:一个又一个循环不执行

JavaScript: Loop after loop not executing

本文关键字:执行 循环 一个又一个 JavaScript      更新时间:2023-09-26

我有这个JavaScript代码,它在单击按钮后执行。for 循环执行正常,但之后的 while 循环根本没有执行。甚至警报也没有执行。

// FAULTY FUNCTION BEGINNING                   
function swap_table_horizontally_vertically() {

  var old_table = document.getElementById('synopsis_table'),
  old_table_rows = old_table.getElementsByTagName('tr'),
  cols = old_table_rows.length, rows = old_table_rows[0].getElementsByTagName('td').length,
  cell, next, temp_row, i = 0, new_table = document.createElement('table');
  // Removes all sort_buttons
  for (i = 0; i <= cols; i++) {
    var sort_buttons = document.getElementById('sort_buttons');
    sort_buttons.parentNode.removeChild(sort_buttons);
  }
  //NOT EXECUTING FROM HERE
  alert("success");
  while(i < rows) {
    cell = 0;
    temp_row = document.createElement('tr');
    if (i == 0) {
      while(cell < cols) {
        next = old_table_rows[cell++].getElementsByTagName('td')[0];
        temp_row.appendChild(next);
      }
      new_table.appendChild(temp_row);
      ++i;
    }
    else {
      while(cell < cols) {
        next = old_table_rows[cell++].getElementsByTagName('td')[0];
        temp_row.appendChild(next);
      }
      new_table.appendChild(temp_row);
      ++i;
    }
  }

  old_table.parentNode.replaceChild(new_table, old_table);
  new_table.setAttribute("id", "synopsis_table");

}
// FAULTY FUNCTION END

我做错了什么?

检查第一个循环循环的次数。因为我认为循环开始时通过 id 'sort_buttons' 删除元素很好,但由于您使用"id",它只会找到一个具有该"id"的元素(您只能有一个带有"id"sort_buttons'的元素)。

因此,当第二次循环时,它不会找到带有"id"sort_buttons"的元素。

在控制台中检查是否有任何错误。

提示:在for循环中添加'console.log(i);'以查看循环循环的次数。

你在 for 循环中迭代 i,所以在第一次循环之后,i 比行高。您可能希望在第二次循环之前设置 i = 0 或使用其他变量。