简体   繁体   English

HTML表中的JS追加行

[英]JS Append Row in HTML Table

I have a hidden field with some values, I have to append these values in HTML table.The number of columns in table is fixed. 我有一个带有一些值的隐藏字段,我必须将这些值附加到HTML表中。表中的列数是固定的。 I have appended successfully,but after first row,it should append data in new row,instead it is appending in the same row. 我已经成功添加了,但是在第一行之后,它应该将数据添加到新行中,而不是在同一行中添加。 This is how I am doing 我就是这样

$("#btntbl").click(function () {
                debugger
                var tabl = $("#testTable");
                var vals = $("#txthidden").val();
                for (var i = 0; i < vals.split(";").length; i++) {                       
                        for (var j = 0; j < vals.split(";")[i].split(",").length; j++) {
                        tabl.append("<td>" + vals.split(";")[i].split(",")[j] + "</td>");
                    }
                }
            });

Also note that some users dont have value of disabled column JS Fiddle How can I add new row each time clicking the button? 还要注意,有些用户没有禁用列JS Fiddle的值。每次单击按钮时,如何添加新行?

You need to split twice and create tr for each row: 您需要拆分两次并为每行创建tr

 $("#btntbl").click(function () { var tabl = $("#testTable"), vals = $("#txthidden").val(), rows = vals.split(';'), columns, i; for (i = 0; i < rows.length; i++) { columns = rows[i].split(','); tabl.append( '<tr>' + '<td>' + columns[0] + '</td>' + '<td>' + columns[1] + '</td>' + '<td>' + (columns[2] || '') + '</td>' + '</tr>' ); } }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <input type="button" id="btntbl" value="Export to table"> <input type="hidden" value="User1,pwd1;User2,pwd2,disabled;User3,pwd3,disabled;User4,pwd4" id="txthidden" /> <table id="testTable" border="2"> <thead valign="top"> <tr> <th>User</th> <th>Password</th> <th>Disabled</th> </tr> </thead> </table> 

Just change target by adding a row 只需添加一行即可更改目标

Change 更改

var tabl = $("#testTable");

To

var tabl = $('<tr>');
$("#testTable").append( tab1);

jsFiddle demo jsFiddle演示

$("#btntbl").click(function () {                  
    var parts = $("#txthidden").val().split(";"), i=0;
    for (;i<parts.length;) {
        var j=0, tr="<tr>", subParts=parts[i++].split(",");          
        for (;j<3;)  tr += "<td>" + (subParts[j++]||"") +"</td>"; // concatenate
        $("#testTable").append( tr +"</tr>" );                    // Append once
    }
});

Here is how you can do it 这是你怎么做

var convertToTable = function (val) {
   val = val.split(';');
   val = val.map(function (v) {
      v = v.split(',');
      if (v.length === 2) v[v.length] = 'NA';
      return '<td>' + v.join('</td><td>') + '</td>';
   });
   val = '<tr>' + val.join('</tr><tr>') + '</tr>';
   return val;
}

and then 接着

tabl.html(convertToTable(vals));

Demo here 在这里演示

您忘记了TD标签,只需在TD之前使用open标签,最后将其关闭

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

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