数据表中的fnAddData()添加到同一行,而不是添加到新行

fnAddData() in datatable adds to same row instead of adding to new rows

本文关键字:添加 新行 一行 fnAddData 数据表      更新时间:2023-09-26

我有一个xml字符串,需要根据该xml数据在数据表中显示。。

var xml = "<Users><user><username>user</username><password>password</password></user><user><username>user1</username><password>password1</password></user><user><username>user2</username><password>password2</password></user></users>";  //this is a sample, but in reality I'm getting the xml string from server
xmlDoc = $.parseXML(xml);  //parsing xml to valid xml document
var $events = $(xmlDoc).find("Users");   
var thisTable;
thisTable = $("#user-data").dataTable(      //user-data is the id of my table
    {
        "sPaginationType": "full_numbers",
        "bJQueryUI": true
   }
);
$events.each(function(index, event){
    console.log('test');
    var $event = $(event),
    addData = [];
    addData.push( $event.children("loan").children("user").children("username").text());
    addData.push($event.children("user").children("password").text());
    thisTable.fnAddData(addData);
});

这是基于的演示

http://jsfiddle.net/jqbv2/

但我遇到了一个非常奇怪的问题,在我的控制台中,"测试"只打印一次,所以每个测试只迭代一次。同样在我的表中,所有用户名都显示在第一行的用户名字段中,所有密码都显示在第一行的密码字段中。也就是说,我在相对时间中使用的数据完全不同,这只是一个例子。这是表格

<table class="table table-striped table-bordered table-hover" id="loan-data">
    <thead>
        <tr>
            <th>Username</th>
            <th>Password</th>
       </tr>
    </thead>
    <tbody>
    </tbody>
</table>

我不明白为什么所有的数据都被添加到一行中,这主要是因为无论有多少数据列表,.each都只迭代一个。它在小提琴的例子中非常有效,但当我尝试进行一些修改时,我会遇到这种冲突。。

这个更新的each应该可以做到这一点:

var eventChildren = $event.children("loan");
eventChildren.each(function(index, event){
    console.log('test');
    var $event = $(event),
    addData = [];
    addData.push( $event.children("user").children("username").text());
    addData.push($event.children("user").children("password").text());
    thisTable.fnAddData(addData);
});

loan包含节点名user的子级。因此,我们需要对loan进行迭代,而不是对文档根进行迭代。