简体   繁体   English

使用 DOM 动态创建表

[英]Dynamic creation of table with DOM

Can someone tell me what's wrong with this code?有人可以告诉我这段代码有什么问题吗? I want to create a table with 2 columns and 3 rows, and in the cells I want Text1 and Text2 on every row.我想创建一个包含 2 列和 3 行的表格,并且在单元格中我希望每一行都有 Text1 和 Text2。 This code creates a table with 2 columns and 3 rows, but it's only text in the cells in the third row (the others are empty).此代码创建一个包含 2 列和 3 行的表格,但它只是第三行单元格中的文本(其他为空)。

var tablearea = document.getElementById('tablearea');

var table = document.createElement('table');

var tr = [];

var td1 = document.createElement('td');
var td2 = document.createElement('td');

var text1 = document.createTextNode('Text1');
var text2 = document.createTextNode('Text2');

for (var i = 1; i < 4; i++){
    tr[i] = document.createElement('tr');   
    for (var j = 1; j < 4; j++){
        td1.appendChild(text1);
        td2.appendChild(text2);
        tr[i].appendChild(td1);
        tr[i].appendChild(td2);
    }           
    table.appendChild(tr[i]);

}

tablearea.appendChild(table);

You must create td and text nodes within loop.您必须在循环内创建 td 和 text 节点。 Your code creates only 2 td, so only 2 are visible.您的代码仅创建 2 个 td,因此只有 2 个可见。 Example:例子:

var table = document.createElement('table');
for (var i = 1; i < 4; i++){
    var tr = document.createElement('tr');   

    var td1 = document.createElement('td');
    var td2 = document.createElement('td');

    var text1 = document.createTextNode('Text1');
    var text2 = document.createTextNode('Text2');

    td1.appendChild(text1);
    td2.appendChild(text2);
    tr.appendChild(td1);
    tr.appendChild(td2);

    table.appendChild(tr);
}
document.body.appendChild(table);

It is because you're only creating two td elements and 2 text nodes.这是因为您只创建了两个td元素和 2 个文本节点。


Creating all nodes in a loop在循环中创建所有节点

Recreate the nodes inside your loop:重新创建循环内的节点:

var tablearea = document.getElementById('tablearea'),
    table = document.createElement('table');

for (var i = 1; i < 4; i++) {
    var tr = document.createElement('tr');

    tr.appendChild( document.createElement('td') );
    tr.appendChild( document.createElement('td') );

    tr.cells[0].appendChild( document.createTextNode('Text1') )
    tr.cells[1].appendChild( document.createTextNode('Text2') );

    table.appendChild(tr);
}

tablearea.appendChild(table);

Creating then cloning in a loop创建然后在循环中克隆

Create them beforehand, and clone them inside the loop:预先创建它们,并在循环内克隆它们:

var tablearea = document.getElementById('tablearea'),
    table = document.createElement('table'),
    tr = document.createElement('tr');

tr.appendChild( document.createElement('td') );
tr.appendChild( document.createElement('td') );

tr.cells[0].appendChild( document.createTextNode('Text1') )
tr.cells[1].appendChild( document.createTextNode('Text2') );

for (var i = 1; i < 4; i++) {
    table.appendChild(tr.cloneNode( true ));
}

tablearea.appendChild(table);

Table factory with text string带有文本字符串的表工厂

Make a table factory:做一个表工厂:

function populateTable(table, rows, cells, content) {
    if (!table) table = document.createElement('table');
    for (var i = 0; i < rows; ++i) {
        var row = document.createElement('tr');
        for (var j = 0; j < cells; ++j) {
            row.appendChild(document.createElement('td'));
            row.cells[j].appendChild(document.createTextNode(content + (j + 1)));
        }
        table.appendChild(row);
    }
    return table;
}

And use it like this:并像这样使用它:

document.getElementById('tablearea')
        .appendChild( populateTable(null, 3, 2, "Text") );

Table factory with text string or callback带有文本字符串或回调的表工厂

The factory could easily be modified to accept a function as well for the fourth argument in order to populate the content of each cell in a more dynamic manner.工厂可以很容易地修改为接受一个函数以及第四个参数,以便以更动态的方式填充每个单元格的内容。

function populateTable(table, rows, cells, content) {
    var is_func = (typeof content === 'function');
    if (!table) table = document.createElement('table');
    for (var i = 0; i < rows; ++i) {
        var row = document.createElement('tr');
        for (var j = 0; j < cells; ++j) {
            row.appendChild(document.createElement('td'));
            var text = !is_func ? (content + '') : content(table, i, j);
            row.cells[j].appendChild(document.createTextNode(text));
        }
        table.appendChild(row);
    }
    return table;
}

Used like this:像这样使用:

document.getElementById('tablearea')
        .appendChild(populateTable(null, 3, 2, function(t, r, c) {
                        return ' row: ' + r + ', cell: ' + c;
                     })
        );

You need to create new TextNodes as well as td nodes for each column, not reuse them among all of the columns as your code is doing.您需要为每一列创建新的 TextNode 和 td 节点,而不是像您的代码那样在所有列中重用它们。

Edit: Revise your code like so:编辑:像这样修改你的代码:

for (var i = 1; i < 4; i++)
{
   tr[i] = document.createElement('tr');   
      var td1 = document.createElement('td');
      var td2 = document.createElement('td');
      td1.appendChild(document.createTextNode('Text1'));
      td2.appendChild(document.createTextNode('Text2'));
      tr[i].appendChild(td1);
      tr[i].appendChild(td2);
  table.appendChild(tr[i]);
}
<title>Registration Form</title>
<script>
    var table;

    function check() {
        debugger;
        var name = document.myForm.name.value;
        if (name == "" || name == null) {
            document.getElementById("span1").innerHTML = "Please enter the Name";
            document.myform.name.focus();
            document.getElementById("name").style.border = "2px solid red";
            return false;
        }
        else {
            document.getElementById("span1").innerHTML = "";
            document.getElementById("name").style.border = "2px solid green";
        }

        var age = document.myForm.age.value;
        var ageFormat = /^(([1][8-9])|([2-5][0-9])|(6[0]))$/gm;

        if (age == "" || age == null) {
            document.getElementById("span2").innerHTML = "Please provide Age";
            document.myForm.age.focus();
            document.getElementById("age").style.border = "2px solid red";
            return false;
        }
        else if (!ageFormat.test(age)) {
            document.getElementById("span2").innerHTML = "Age can't be leass than 18 and greater than 60";
            document.myForm.age.focus();
            document.getElementById("age").style.border = "2px solid red";
            return false;
        }
        else {
            document.getElementById("span2").innerHTML = "";
            document.getElementById("age").style.border = "2px solid green";
        }

        var password = document.myForm.password.value;
        if (document.myForm.password.length < 6) {
            alert("Error: Password must contain at least six characters!");
            document.myForm.password.focus();
            document.getElementById("password").style.border = "2px solid red";
            return false;
        }
        re = /[0-9]/g;
        if (!re.test(password)) {
            alert("Error: password must contain at least one number (0-9)!");
            document.myForm.password.focus();
            document.getElementById("password").style.border = "2px solid red";
            return false;
        }
        re = /[a-z]/g;
        if (!re.test(password)) {
            alert("Error: password must contain at least one lowercase letter (a-z)!");
            document.myForm.password.focus();
            document.getElementById("password").style.border = "2px solid red";
            return false;
        }
        re = /[A-Z]/g;
        if (!re.test(password)) {
            alert("Error: password must contain at least one uppercase letter (A-Z)!");
            document.myForm.password.focus();
            document.getElementById("password").style.border = "2px solid red";
            return false;
        }
        re = /[$&+,:;=?@#|'<>.^*()%!-]/g;
        if (!re.test(password)) {
            alert("Error: password must contain at least one special character!");
            document.myForm.password.focus();
            document.getElementById("password").style.border = "2px solid red";
            return false;
        }
        else {
            document.getElementById("span3").innerHTML = "";
            document.getElementById("password").style.border = "2px solid green";

        }

        if (document.getElementById("data") == null)
            createTable();
        else {
            appendRow();
        }
        return true;
    }






    function createTable() {

        var myTableDiv = document.getElementById("myTable");  //indiv
        table = document.createElement("TABLE");   //TABLE??
        table.setAttribute("id", "data");
        table.border = '1';
        myTableDiv.appendChild(table);  //appendChild() insert it in the document (table --> myTableDiv)
        debugger;

        var header = table.createTHead();

        var th0 = table.tHead.appendChild(document.createElement("th"));
        th0.innerHTML = "Name";
        var th1 = table.tHead.appendChild(document.createElement("th"));
        th1.innerHTML = "Age";


        appendRow();

    }

    function appendRow() {
        var name = document.myForm.name.value;
        var age = document.myForm.age.value;


        var rowCount = table.rows.length;
        var row = table.insertRow(rowCount);

        row.insertCell(0).innerHTML = name;
        row.insertCell(1).innerHTML = age;



        clearForm();


    }


    function clearForm() {
        debugger;

        document.myForm.name.value = "";
        document.myForm.password.value = "";
        document.myForm.age.value = "";



    }
    function restrictCharacters(evt) {

        evt = (evt) ? evt : window.event;
        var charCode = (evt.which) ? evt.which : evt.keyCode;
        if (((charCode >= '65') && (charCode <= '90')) || ((charCode >= '97') && (charCode <= '122')) || (charCode == '32')) {
            return true;
        }
        else {
            return false;
        }
    }

</script>



<div>
    <form name="myForm">

        <table id="tableid">

            <tr>
                <th>Name</th>
                <td>
                    <input type="text" name="name" placeholder="Name" id="name" onkeypress="return restrictCharacters(event);" /></td>
                <td><span id="span1"></span></td>
            </tr>

            <tr>
                <th>Age</th>

                <td>
                    <input type="text" onkeypress="return event.charCode === 0 || /\d/.test(String.fromCharCode(event.charCode));" placeholder="Age"
                        name="age" id="age" /></td>
                <td><span id="span2"></span></td>
            </tr>

            <tr>
                <th>Password</th>
                <td>
                    <input type="password" name="password" id="password" placeholder="Password" /></td>
                <td><span id="span3"></span></td>
            </tr>


            <tr>
                <td></td>
                <td>
                    <input type="button" value="Submit" onclick="check();" /></td>
                <td>
                    <input type="reset" name="Reset" /></td>
            </tr>

        </table>
    </form>

    <div id="myTable">
    </div>

</div>
var html = "";
    for (var i = 0; i < data.length; i++){
    html +="<tr>"+
            "<td>"+ (i+1) + "</td>"+
            "<td>"+ data[i].name + "</td>"+
            "<td>"+ data[i].number + "</td>"+
            "<td>"+ data[i].city + "</td>"+
            "<td>"+ data[i].hobby + "</td>"+
            "<td>"+ data[i].birthdate + "</td>"+"<td><button data-arrayIndex='"+ i +"' onclick='editData(this)'>Edit</button><button data-arrayIndex='"+ i +"' onclick='deleteData()'>Delete</button></td>"+"</tr>";
}
$("#tableHtml").html(html);

In my example, serial number is managed according to the actions taken on each row using css.在我的示例中,根据使用 css 对每一行采取的操作来管理序列号。 I used a form inside each row, and when new row created then the form will get reset.我在每一行内使用了一个表单,当创建新行时,表单将被重置。

 /*auto increment/decrement the sr.no.*/ body { counter-reset: section; } i.srno { counter-reset: subsection; } i.srno:before { counter-increment: section; content: counter(section); } /****/
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <script type='text/javascript'> $(document).ready(function () { $('#POITable').on('change', 'select.search_type', function (e) { var selectedval = $(this).val(); $(this).closest('td').next().html(selectedval); }); }); </script> <table id="POITable" border="1"> <tr> <th>Sl No</th> <th>Name</th> <th>Your Name</th> <th>Number</th> <th>Input</th> <th>Chars</th> <th>Action</th> </tr> <tr> <td><i class="srno"></i></td> <td> <select class="search_type" name="select_one"> <option value="">Select</option> <option value="abc">abc</option> <option value="def">def</option> <option value="xyz">xyz</option> </select> </td> <td></td> <td> <select name="select_two" > <option value="">Select</option> <option value="123">123</option> <option value="456">456</option> <option value="789">789</option> </select> </td> <td><input type="text" size="8"/></td> <td> <select name="search_three[]" > <option value="">Select</option> <option value="one">1</option> <option value="two">2</option> <option value="three">3</option> </select> </td> <td><button type="button" onclick="deleteRow(this)">-</button><button type="button" onclick="insRow()">+</button></td> </tr> </table> <script type='text/javascript'> function deleteRow(row) { var i = row.parentNode.parentNode.rowIndex; document.getElementById('POITable').deleteRow(i); } function insRow() { var x = document.getElementById('POITable'); var new_row = x.rows[1].cloneNode(true); var len = x.rows.length; //new_row.cells[0].innerHTML = len; //auto increment the srno var inp1 = new_row.cells[1].getElementsByTagName('select')[0]; inp1.id += len; inp1.value = ''; new_row.cells[2].innerHTML = ''; new_row.cells[4].getElementsByTagName('input')[0].value = ""; x.appendChild(new_row); } </script>

Hope this helps.希望这可以帮助。

In My example call add function from button click event and then get value from form control's and call function generateTable.在我的示例中,从按钮单击事件调用 add 函数,然后从表单控件和调用函数 generateTable 中获取值。
In generateTable Function check first Table is Generaed or not.在 generateTable 函数中首先检查表是否已生成。 If table is undefined then call generateHeader Funtion and Generate Header and then call addToRow function for adding new row in table.如果 table 未定义,则调用 generateHeader 函数和 Generate Header,然后调用 addToRow 函数在表中添加新行。

<input type="button" class="custom-rounded-bttn bttn-save" value="Add" id="btnAdd" onclick="add()">


<div class="row">
    <div class="col-lg-12 col-md-12 col-sm-12 col-xs-12">
        <div class="dataGridForItem">
        </div>
    </div>
</div>

//Call Function From Button click Event

var counts = 1;
function add(){ 
    var Weightage = $('#Weightage').val();
    var ItemName = $('#ItemName option:selected').text();  
    var ItemNamenum = $('#ItemName').val();
    generateTable(Weightage,ItemName,ItemNamenum);
     $('#Weightage').val('');
     $('#ItemName').val(-1);
     return true;
 } 


function generateTable(Weightage,ItemName,ItemNamenum){
    var tableHtml = '';
    if($("#rDataTable").html() == undefined){
        tableHtml = generateHeader();
    }else{
        tableHtml = $("#rDataTable");
    } 
    var temp = $("<div/>");
    var row = addToRow(Weightage,ItemName,ItemNamenum);
    $(temp).append($(row));
    $("#dataGridForItem").html($(tableHtml).append($(temp).html()));
}


//Generate Header


function generateHeader(){
        var html = "<table id='rDataTable' class='table table-striped'>";
        html+="<tr class=''>";
        html+="<td class='tb-heading ui-state-default'>"+'Sr.No'+"</td>";
        html+="<td class='tb-heading ui-state-default'>"+'Item Name'+"</td>";
        html+="<td class='tb-heading ui-state-default'>"+'Weightage'+"</td>";
        html+="</tr></table>";
        return html; 
}

//Add New Row


function addToRow(Weightage,ItemName,ItemNamenum){
    var html="<tr class='trObj'>";
    html+="<td>"+counts+"</td>";
    html+="<td>"+ItemName+"</td>";
    html+="<td>"+Weightage+"</td>";
    html+="</tr>";
    counts++;
    return html;
}

You can create a dynamic table rows as below:您可以创建一个动态表行,如下所示:

var tbl = document.createElement('table');
tbl.style.width = '100%';

for (var i = 0; i < files.length; i++) {

        tr = document.createElement('tr');

        var td1 = document.createElement('td');
        var td2 = document.createElement('td');
        var td3 = document.createElement('td');

        ::::: // As many <td> you want

        td1.appendChild(document.createTextNode());
        td2.appendChild(document.createTextNode());
        td3.appendChild(document.createTextNode();

        tr.appendChild(td1);
        tr.appendChild(td2);
        tr.appendChild(td3);

        tbl.appendChild(tr);
}

You can do that using LemonadeJS.你可以使用 LemonadeJS 来做到这一点。

<html>
<script src="https://lemonadejs.net/v2/lemonade.js"></script>
<div id='root'></div>
<script>
var Component = (function() {
    var self = {};
 
    self.rows = [
        { title:'Google', description: 'The alpha search engine...' },
        { title:'Bind', description: 'The microsoft search engine...' },
        { title:'Duckduckgo', description: 'Privacy in the first place...' },
    ];
 
    // Custom components such as List should always be unique inside a real tag.
    var template = `<table cellpadding="6">
            <thead><tr><th>Title</th><th>Description</th></th></thead>
            <tbody @loop="self.rows">
            <tr><td>{{self.title}}</td><td>{{self.description}}</td></tr>
            </tbody>
        </table>`;
 
    return lemonade.element(template, self);
});
 
lemonade.render(Component, document.getElementById('root'));
</script>
</html>

when you say 'appendchild' you actually move your child from one parent to another.当您说“appendchild”时,您实际上是将您的孩子从一位家长转移到了另一位家长。 you have to create a node for each cell.您必须为每个单元格创建一个节点。

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

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