2013-08-20 45 views
0

我在想如何用for循环创建一个函数,为其他for循环创建新的单元格/行。该函数应该返回newRow,它应该是指定数量的单元格。这个想法是HTML代码每行显示3个图像,但如果只有2个图像,那么它只需要2个单元格。这是第一个if/else语句。动态创建一个表格并通过一个带有Javascript的函数向表格中添加单元格

这里是到目前为止的代码..

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 

} 

}

回答

1

这里,如果你不希望传递的价值观,你可以离开content了一个简单的函数。

function newRow(numberOfCells, content) 
{ 
var result = '<tr>'; 
for(var i = 0; i < numberOfCells; i++) 
    result += '<td>' + content[i] + '</td>'; 
result += '</tr>'; 
return result; 
} 
相关问题