用 jquery 填充 html 表
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7196238/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
populate html table with jquery
提问by Thomas
suppose i have table and i want to append data in the middle of table through jquery.
假设我有表,我想通过 jquery 在表中间附加数据。
here is my table code html
这是我的表格代码 html
<table border="1">
<tr>
<th>Header 1</th>
<th>Header 2</th>
</tr>
here i need to append tr with jQuery
在这里我需要用 jQuery 附加 tr
<tr>
<td>row 2, cell 1</td>
<td>row 2, cell 2</td>
</tr>
</table>
is it possible with jquery? if so then please guide me. if i can populate then i can do like
jquery可以吗?如果是这样,请指导我。如果我可以填充,那么我可以这样做
for (var i = 0; i < data.d.length; i++) {
$("#NamesGridView").append("<tr><td>" + data.d[i].FirstName +
"</td><td>" + data.d[i].Age + "</td></tr>");
}
}
please guide thanks
请指导谢谢
回答by Paul
回答by Muhammad Kashif
Below Code will populate html table with jquery.
下面的代码将使用 jquery 填充 html 表。
<table id="tablefriendsname">
<tbody>
</tbody>
</table>
$.ajax({
type: "POST",
url: "/users/index/friendsnamefromids",
data: "IDS="+requests,
dataType: "json",
success: function(response){
var name = response;
//Important code starts here to populate table
var yourTableHTML = "";
jQuery.each(name, function(i,data) {
$("#tablefriendsname").append("<tr><td>" + data + "</td></tr>");
});
}
});
回答by Andrew
If you are adding the data in for loop, it would be more performant to build the string first then add it all in one call.
如果您在 for 循环中添加数据,则先构建字符串然后在一次调用中添加所有字符串会更高效。
var newRows = "";
for (var i = 0; i < data.d.length; i++) {
newRows += "<tr><td>" + data.d[i].FirstName +
"</td><td>" + data.d[i].Age + "</td></tr>";
}
$("table tr:first").after(newRows);
回答by scessor
Add the id NamesGridView
to the first tr
添加id NamesGridView
到第一个tr
<table border="1">
<tr id="NamesGridView">
<th>Header 1</th>
<th>Header 2</th>
</tr>
<tr>
<td>row 2, cell 1</td>
<td>row 2, cell 2</td>
</tr>
</table>
and change the append
to after
.
并将 更改append
为after
。
for (var i = 0; i < data.d.length; i++) {
$("#NamesGridView").after("<tr><td>" + data.d[i].FirstName + "</td><td>" + data.d[i].Age + "</td></tr>");
}
Also see my jsfiddle.
另请参阅我的jsfiddle。