如何在jQuery中创建动态表?

时间:2016-04-25 07:01:29

标签: javascript jquery html

我想在jQuery中创建一个动态表。但是我的代码为我的每个元素创建了一个表。

var dataItem = this.dataItem($(e.currentTarget).closest("tr"));
var str = dataItem.Description;
var spl = str.split(','), part;
var spl2 = "";
for (var i = 0; i < spl.length; i++) {
    part = spl[i].split(':');
    content = "<table>" + "<tr><td>" + part[0] + "</td>" + "<td>" + part[1] + "</td></tr>";
    spl2 += content;
}
content += "</table>"
var desc = "<div id='openModal' class='modalDialog'>" + "<span>" +
    spl2
    + "</span><br/>" +
    +  "</div>";

我的代码中哪一部分错了?

2 个答案:

答案 0 :(得分:1)

当你在for循环中添加表时,所以它为每个项创建表。试试这个:

var dataItem = this.dataItem($(e.currentTarget).closest("tr"));
var str = dataItem.Description;
var spl = str.split(','), part;
var spl2 = "";
content ="<table>"
 for (var i = 0; i < spl.length; i++) {
     part = spl[i].split(':');
     content += "<tr><td>" + part[0] + "</td>" + "<td>" + part[1] + "</td></tr>";
     spl2 = content;
 }
content += "</table>"

// you can also assign spl2 = content; over here.
    var desc = "<div id='openModal' class='modalDialog'>" + "<span>" +
        spl2
        + "</span><br/>" +
        +  "</div>";

答案 1 :(得分:0)

    var dataItem = this.dataItem($(e.currentTarget).closest("tr"));
var str = dataItem.Description;
var spl = str.split(','), part;
var spl2 = "";
var content = "<table>";
 for (var i = 0; i < spl.length; i++) {
     part = spl[i].split(':');
     content += "<tr><td>" + part[0] + "</td>" + "<td>" + part[1] + "</td></tr>";
     spl2 += content;
 }
content += "</table>"
var desc = "<div id='openModal' class='modalDialog'>" + "<span>" +
    spl2
    + "</span><br/>" +
    +  "</div>";

更新了您的脚本