我想知道如何创建一个带有 for 循环的函数,该循环为另一个 for 循环调用创建新的单元格/行。该函数应返回 newRow,它应该是指定数量的单元格。这个想法是 html 代码每行显示 3 个图像,但如果只有 2 个图像,那么它只需要 2 个单元格。这是第一个 if / else 语句。
这是到目前为止的代码..
var cells = document.getElementsByTagName('td');
var cell = '<td>' + cells[0].innerHTML + '</td>';
//console.log(cell);
document.getElementById('searchBtn').onclick = search;
//specified as 3 per row
var NUMPERROW = 3;
//gets number from form text input
var num = document.getElementById("searchtxt").value;
function search(){
//var num = 4;
console.log(num);
//loop once per row
var htmlStr = '';
for (var i = 0; i < num; i = i + NUMPERROW){
//htmlStr += '<tr>' + cell + cell + cell + '</tr>;
if (num - i >= NUMPERROW) {
//displays a new row of 3
htmlStr += newRow(NUMPERROW);
}else { //less then 3 to display
htmlStr += newRow(num - i);
}
}
document.getElementById('thumbnails').innerHTML = htmlStr;
}
/*
*Returns the html for a new row.
* numToAdd: the number of cells to add for this row.
*
*/
//this function i do not know how to write
function newRow(cellsToAdd){
/////?????????? should be a for loop return new Row for the for loop above
}
}