JavaScript:一个又一个循环不执行
JavaScript: Loop after loop not executing
我有这个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 或使用其他变量。
相关文章:
- 未执行Ajax循环的Javascript之后的代码
- 虽然循环不执行或不循环
- 为什么AngularJS在每个摘要循环上都执行函数
- javascript代码不会在循环后执行
- Chrome浏览器“;挂起”;同时在循环中执行AJAX请求
- 当JSON数据=变量时,需要执行循环
- 如何优化这个jquery循环的执行时间
- 如何在Javascript中延迟for循环执行
- 我将如何在 for 循环中执行此操作
- 了解执行模型和事件循环
- for 循环/递归中的执行顺序
- 如何在完成完全执行函数后触发循环
- 执行在外循环的第一次迭代后停止
- jquery .each 循环来执行每个数组项,它们之间有延迟
- 首先执行循环外的代码
- 如何使用内函数的回调值执行循环
- 以连续的方式执行循环中的所有元素
- 当我执行循环时,AngularJs/Ajax索引正在改变
- 在变量内执行循环
- 在JavaScript中执行循环的最佳方式是什么