JavaScript:循环后循环不执行

时间:2014-11-24 11:42:37

标签: javascript loops

我有这个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

我做错了什么?

2 个答案:

答案 0 :(得分:0)

检查第一个循环循环的次数。因为我认为通过id&#39; sort_buttons&#39;删除元素,循环开始很好。但是因为你正在使用&#39; id&#39;它只会找到一个带有“id”的元素。 (你只能有一个带有&#39; id&#39; sort_buttons&#39;的元素。

因此,当第二次循环时,它将找不到具有&#39; id&#39; &#39; sort_buttons&#39;

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

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

答案 1 :(得分:0)

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

相关问题