$('#all_locations').append("<table>");
$('#all_locations').append("<tr><th>City</th></tr>");
$.each(data, function(i, item){
$('#all_locations').append("<tr>");
$('#all_locations').append("<td>"+item.city+"</td>");
$('#all_locations').append("<tr>");
}
$('#all_locations').append("</table>");
使用alert($('#all_locations').html());
<table></table>
<tr><th>City</th></tr>
<tr></tr><td>Seattle</td>
<tr></tr><td>Chicago</td>
当ajax调用完成时,此代码将触发。任何想法为什么会这样做?
假设数据变量是有效的JSON对象。
答案 0 :(得分:14)
尽管jQuery提供了抽象,但您在DOM中运行元素,而不是HTML源代码中的标记。
jQuery('<table>')
是jQuery(document.createElement('table'))
的缩写。
您需要将表行附加到表中,而不是附加到容器中(同样,需要将单元格添加到行中)。
答案 1 :(得分:4)
最佳做法是创建HTML字符串以追加并对该字符串运行一次.append()
调用:
//declare our output variable
var output = '<table><tr><th>City</th></tr>';
//iterate through data
$.each(data, function(i, item){
//add to output variable
output += '<tr><td>' + item.city + '</td></tr>';
}
//append the output to the DOM
$('#all_locations').append(output);
通常会看到人们将项目推送到数组中并将该数组加入到追加中:
//declare our output variable (array)
var output = ['<table><tr><th>City</th></tr>'];
//iterate through data
$.each(data, function(i, item){
//add to output variable
output.push('<tr><td>' + item.city + '</td></tr>');
}
//append the output to the DOM after joining it together into a string
$('#all_locations').append(output.join(''));
答案 2 :(得分:0)
在代码中添加id
以解决此问题。
然后将子元素添加到id
而不是父元素。
$(function(){
for(var lvl=0;lvl<5;lvl++)
{
$("#tblId tbody").append("<tr id="+lvl+"/>");
for(var fchr=0;fchr<3;fchr++)
$("#tblId tbody #"+lvl).append("<td>Val"+lvl+fchr+"</td>");
}
alert($('#tblId').html());
});
运行示例,请参见此处: http://jsfiddle.net/WHscf/1/
答案 3 :(得分:-1)
不要这样做,尝试这样的事情:
var table = $("<table>");
if (table){
table.append($("<tr>").append($("<th>").text("City")));
$.each(data, function(i, item){
table.append($("<tr>").append($("<td>").text(item.city)));
});
table.appendTo($("#all_locations"));
}
这是另一种更接近你目前如何做的方式:
$("#all_locations""#all_locations").append("<tr><th>City</th></tr>");
$.each(data, function(i, item){
$('#all_locations').append("<tr>");
$('#all_locations').append("<td>""<tr><td>" + item.city + "</td>"td></tr>");
$('#all_locations').append("<tr>"});
}
$("#all_locations tr").wrapAll("<table></table>");