我正在通过JSON数据动态创建表,但是将所有<td>
个元素放在同一个<tr>
而不是两个不同的行中。
JavaScript部分:
$('button').click(function() {
var str = '[{"callType":"IN","extension":"150","name":"avis","phoneNumber":"9876541230","skill":"English","status":"INCALL","time":"10:50:23"},{"callType":"OUT","extension":"857","name":"sys","phoneNumber":"9658741235","skill":"Hindi","status":"WAITING","time":"08:40:51"}]';
var list = JSON.parse(str);
for (var i = 0; i < list.length; i++) {
var tr = $('#t').append('<tr class="laOriginal" value="user"></tr>');
var radioBtn = $('<input type="radio" name="radioAgent" value="' + list[i].name + '" />" id="radioAgent' + list[i].name + '"');
tr.append(radioBtn);
tr.append("<td>" + list[i].name + "</td>");
tr.append("<td>" + list[i].extension + "</td>");
tr.append("<td>" + list[i].skill + "</td>");
tr.append("<td>" + list[i].phoneNumber + "</td>");
tr.append("<td>" + list[i].status + "</td>");
tr.append("<td>" + list[i].callType + "</td>");
tr.append("<td>" + list[i].time + "</td>");
}
});
小提琴:Fiddle
如何在两个不同的行中获取数据?
答案 0 :(得分:7)
这一行:
var tr = $('#t').append('<tr class="laOriginal" value="user"></tr>');
实际上返回与$('#t')
相关的jQuery对象,而不是生成的<tr>
元素。您应该交换语法并使用appendTo()
:
var tr = $('<tr class="laOriginal" value="user"></tr>').appendTo('#t');
答案 1 :(得分:0)
您的var tr
是$('#t')的值,而不是附加代码的值。
您要做的是:http://jsfiddle.net/s3rbG/5/
也就是说,将新创建的tr保存在var中,然后将其附加到表中。这样,当你向它添加td元素时,它们会被添加到tr而不是表中。
答案 2 :(得分:0)
$('button').click(function() {
var str = '[{"callType":"IN","extension":"150","name":"avis","phoneNumber":"9876541230","skill":"English","status":"INCALL","time":"10:50:23"},{"callType":"OUT","extension":"857","name":"sys","phoneNumber":"9658741235","skill":"Hindi","status":"WAITING","time":"08:40:51"}]';
var list = JSON.parse(str);
for (var i = 0; i < list.length; i++) {
var new_tr = $('#t').append('<tr class="laOriginal" value="user"></tr>');
var last_tr = $('#t tr :last' );
var radioBtn = $('<input type="radio" name="radioAgent" value="' + list[i].name + '" />" id="radioAgent' + list[i].name + '"');
last_tr.append(radioBtn);
last_tr.append("<td>" + list[i].name + "</td>");
last_tr.append("<td>" + list[i].extension + "</td>");
last_tr.append("<td>" + list[i].skill + "</td>");
last_tr.append("<td>" + list[i].phoneNumber + "</td>");
last_tr.append("<td>" + list[i].status + "</td>");
last_tr.append("<td>" + list[i].callType + "</td>");
last_tr.append("<td>" + list[i].time + "</td>");
}
});