添加表格行和单元格 [英] Adding table rows and cells

查看:112
本文介绍了添加表格行和单元格的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图使页面在每个表中添加行和五个单元格,但是我遇到了一些问题.我首先将行添加到表中,然后循环遍历并在每行中添加五个单元格,但是,每当我在网络浏览器中运行它时,都会产生以下内容:

I tried to make the page add rows and five cells to each table, however I'm having some problems. I appended the row first to the table then followed by looping through the and adding five cells to each row, however whenever I ran it in my web browser it produced this:

我希望单元格成为表行的子项.

I want the cells to be a child of the table row.

function addRows(ramnt) {
  if(ramnt > 0){
    var cellcount = 5;
    var tccount = 0;
    table.append('<tr>');
    console.log('Appended <tr>');
    while(tccount < cellcount){
        tccount = tccount + 1;
        table.append('<td id="Cell-' + tccount  + '" class="gencell"></td>');
    } 
    if (tccount = cellcount){
      table.append('</tr>');
      ramnt = ramnt - 1;
      addRows(ramnt);
    }
  }
}

console.log('Working');
var table = $('Table');
addRows(5);

推荐答案

我建议使您的函数更具动态性.这是我的建议:

I would advise making your function a little more dynamic. Here is what I would suggest:

function addRows(rc, to) {
  if(rc > 0){
    var cellcount = 5;

    for(var i = 0; i < rc; i++){
        var row = $("<tr>", { id: "Row-" + i });
        for(var c = 0; c < cellcount; c++){
            row.append("<td id='Cell-" + c + "' class='gencell'></td>");
        }
        to.append(row);
        console.log("Row " + i + " created");
    }
    return true;
  } else {
    return false;
  }
}

然后,您可以像这样传递行数和表对象:

Then you can pass the Number of Rows and the Table Object like so:

addRows(5, $("table"));

正如我所说,我建议像这样设置您的餐桌:

As I said, I would advise setting your table like so:

<table id="myTable"></table>

这样,如果以后添加另一个表或执行其他操作,仍然可以使用相同的代码:

This way if you later add another table or do something differnt, you can still use the same code:

addRows(5, $("#myTable"));

工作示例: https://jsfiddle.net/Twisty/Lysr2n5v/

您可以进一步编写函数以接受X个行,N个每行单元格和表对象:

You can take a bit further to write to function to accept X number of Rows, N number of Cells per Row, and the table Object: https://jsfiddle.net/Twisty/Lysr2n5v/2/

function addRows(rc, cc, to) {
  if(rc > 0){
    for(var i = 0; i < rc; i++){
        var row = $("<tr>", { id: "Row-" + i });
        for(var c = 0; c < cc; c++){
            row.append("<td id='Cell-" + c + "' class='gencell'></td>");
        }
        to.append(row);
        console.log("Row " + i + " created");
    }
    return true;
  } else {
    return false;
  }
}

这篇关于添加表格行和单元格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆