如何在表格单元格中插入标签文本

时间:2018-10-15 12:44:55

标签: javascript c# asp.net

我有一个表格,该表格是根据用户输入动态生成的。我试图在单击按钮时将标签文本插入表格单元格。在按钮的onclick上,应将演示方法的标签文本插入表格单元格中。有人可以建议我该怎么做?

谢谢。

创建表格:

function CreateTable(){
    var rowCtr;
    var cellCtr;
    var rowCnt;
    var cellCnt;

    var myTableDiv = document.getElementById('myDynamicTable');

    var table = document.createElement('table');
    table.setAttribute("contenteditable", "true");
    table.border = "1";
    table.id = "myTable";


    var tableBody = document.createElement('tbody');
    table.appendChild(tableBody);

    rowCnt = document.getElementById('txtrows').value;
    cellCnt = document.getElementById('txtcols').value;

    for (rowCtr = 0; rowCtr < rowCnt; rowCtr++) {

        var tr = document.createElement('tr');
        tableBody.appendChild(tr);

        for (cellCtr = 0; cellCtr < cellCnt; cellCtr++) {

            var td = document.createElement('td');
            td.width = '120';
            td.appendChild(document.createTextNode("Row:" + rowCtr + " Column:" + cellCtr));
            tr.appendChild(td);
        }
    }
    myTableDiv.appendChild(table);
  }

按钮:

<asp:Button ID="button1" Text="button" runat="server" OnClick="demo" />

C#代码:

 public void demo()
    {
        TableCell tcell = new TableCell();
        RadLabel rlbl = new RadLabel();
        rlbl.Text = "test";
        tcell.Controls.Add(rlbl);

    }

    protected void demo(object sender, EventArgs e)
    {
        demo();
    }

1 个答案:

答案 0 :(得分:0)

要开始使用Javascript,可以使用以下代码作为起点。

window.onload=function(){
CreateTable();
}
function CreateTable(){
    var rowCtr;
    var cellCtr;
    var rowCnt;
    var cellCnt;

    var myTableDiv = document.getElementById('myDynamicTable');

    var table = document.createElement('table');
    table.setAttribute("contenteditable", "true");
    table.border = "1";
    table.id = "myTable";


    var tableBody = document.createElement('tbody');
    table.appendChild(tableBody);

    rowCnt = 3; //document.getElementById('txtrows').value;
    cellCnt =2; //document.getElementById('txtcols').value;

    for (rowCtr = 0; rowCtr < rowCnt; rowCtr++) {

        var tr = document.createElement('tr');
        tableBody.appendChild(tr);

        for (cellCtr = 0; cellCtr < cellCnt; cellCtr++) {

            var td = document.createElement('td');
            td.width = '120';
            td.appendChild(document.createTextNode("Row:" + rowCtr + " Column:" + cellCtr));
            tr.appendChild(td);
        }
    }
    myTableDiv.appendChild(table);
  }

function demo(){
var myTable=document.getElementById('myTable');
var cell=myTable.rows[0].cells[1];
var label = document.createElement('label');
label.id="lbl-"+cell.cellIndex;
label.innerText="This is label text";
cell.appendChild(label);
}
<input type="button" onclick="demo()" value="Create Label" />
<div id="myDynamicTable"></div>