附加:第n个孩子使用循环

时间:2015-10-09 01:35:31

标签: jquery

我的问题是如何在我追加的第一个tr上附加第一个信息等等。

这是我的代码

$('.table').append('<tbody>');
    console.log(tableBody.length);

    //count tbody tbody_tr
    var tbody_tr = tableBody.length / unique_header.length;

    //count how many column / row 
    var tbody_td = tableBody.length / tbody_tr;

    console.log('every td' + tbody_td + 'body tr' + tbody_tr);
    for(appendCountBody = 0; appendCountBody < tbody_tr; appendCountBody++){

        $('.table tbody').append('<tr>');

        $('.table tbody').append('</tr>');

    }

    //tbody tr td
    var counter = 0;
    for(appendCountBodyTd = 0; appendCountBodyTd < tableBody.length; appendCountBodyTd++){

        if(counter < tbody_td){
            console.log(counter + ':' + tbody_td+ ':' + tableBody[appendCountBodyTd] );
            $('.table tbody tr').append('<td>'+tableBody[appendCountBodyTd]+'</td>');
            counter = counter + 1;
        }else{
            counter = 0;
        }
    }

$('.table').append('</tbody>');

这是信息的图像以及它在我的浏览器中的样子

enter image description here

enter image description here

提前感谢。

1 个答案:

答案 0 :(得分:1)

您必须修复$("table")选择器以匹配您的DOM,但这里有基本想法:

$(document).ready(function() {

    var testData = [
        "1", "John", "Doe",
        "2", "Ralph", "Garcia",
        "3", "John", "Jean"
    ];

    for(var i = 0; i < testData.length; i+= 3) {
        $("table").append(
            $("<tr>")
                .append(
                    $("<td>").html(testData[i + 0]),
                    $("<td>").html(testData[i + 1]),
                    $("<td>").html(testData[i + 2])
                )
        );
    }
});

如果每个&#34;记录&#34;的长度在你的传入列表中可能会有所不同,你可以使用更灵活的东西:

$(document).ready(function() {

    var testData = [
        "1", "John", "Doe", "alpha",
        "2", "Ralph", "Garcia", "beta",
        "3", "John", "Jean", "gamma"
    ];

    var recordLength = 4;

    for(var i = 0; i < testData.length; i += recordLength) {
        $newRow = $("<tr>");
        for(var j = 0; j < recordLength; j++) {
            $newRow.append(
                $("<td>").html(testData[i + j])
            );
        }

        $("table").append($newRow);
    }
});

但理想情况下,数据应该在另一端更好地打包,以便它作为数组数组或对象数组进入。下面是一个包含数组数组(长度不同)的示例:

$(document).ready(function() {

    var testData = [
        ["1", "John", "Doe", "alpha", "beta"],
        ["2", "Ralph", "Garcia", "gamma"],
        ["3", "John", "Jean", "delta", "epsilon"]
    ];

    for(var i = 0; i < testData.length; i++) {
        $newRow = $("<tr>");
        for(var j = 0; j < testData[i].length; j++) {
            $newRow.append(
                $("<td>").html(testData[i][j])
            );
        }
        $("table").append($newRow);
    }
});