简体   繁体   English

如何在td标签中插入输入标签?

[英]How to insert input tag in to td tag?

I have code which generate table. 我有生成表的代码。 You can see below the code: 您可以在下面看到代码:

function createDynamicTable(tbody, rows, cols) {
         if (tbody == null || tbody.length < 1) return;
         for (var r = 1; r <= rows; r++) {
             var trow = $("<tr>");
             for (var c = 1; c <= cols; c++) {
                 var cellText = "Cell " + r + "." + c
                 $("<td>")
                         .addClass("tableCell")
                         .text(cellText)
                         .data("col", c)
                         .appendTo(trow);
             }
             trow.appendTo(tbody);
         }
     }      

the results are: 结果是:

<table id="tbl" border="1">
<tbody>
<tr>
<td class="tableCell">Cell 1.1</td>
<td class="tableCell">Cell 1.2</td>
<td class="tableCell">Cell 1.3</td>
<td class="tableCell">Cell 1.4</td>
</tr>
</tbody>
</table>

I wish to add each <td></td> => <td><input><input/></td> Tagas. 我希望添加每个<td></td> => <td><input><input/></td> Tagas。 How I can do that? 我怎么能这样做?

Modify your function a bit, and it will add input fields to each cell: 稍微修改你的函数,它会为每个单元格添加input字段:

function createDynamicTable(tbody, rows, cols) {
    if (tbody == null || tbody.length < 1) return;
    for (var r = 1; r <= rows; r++) {
        var trow = $("<tr>");
        for (var c = 1; c <= cols; c++) {
            var input = $("<input />");
            $("<td>").addClass("tableCell")
                .append(input)
                .data("col", c)
                .appendTo(trow);
        }
        trow.appendTo(tbody);
    }
}

DEMO: http://jsfiddle.net/Xt33h/ 演示: http //jsfiddle.net/Xt33h/

你可以这样做:

$('#tbl td:last').after('<td><input><input/></td>');

change the for (where you produces the cells) as 将for(生成单元格的位置)更改为

for (var c = 1; c <= cols; c++) {
    var cellText = "Cell " + r + "." + c
    var td = $("<td>")
        .addClass("tableCell")
        .text(cellText)
        .data("col", c)
        .appendTo(trow);

    $('<input />').appendTo(td);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM