jQuery附加表自动在文本末尾添加结束标记。为什么?

时间:2011-11-10 18:45:24

标签: jquery html json html-table append

$('#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对象。

4 个答案:

答案 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>");