2011-11-10 92 views
3
$('#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());jQuery附加表自動在文本末尾添加結束標記。爲什麼?

<table></table> 
<tr><th>City</th></tr> 
<tr></tr><td>Seattle</td> 
<tr></tr><td>Chicago</td> 

此代碼在ajax調用完成時觸發。任何想法爲什麼會這樣做?

假設數據變量是有效的JSON對象。

回答

14

儘管jQuery提供,你在元素在DOM,沒有標籤的HTML源工作的抽象。

jQuery('<table>')jQuery(document.createElement('table'))簡寫。

您需要將表中的行追加到表,而不是到容器(同樣地,細胞需要被添加到該行)。

+0

哇不知道..它有一定道理,但因爲每當我不關閉的append()內的標籤,它會做它對我來說......謝謝! – Sherzod

-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>"); 
+0

最後一行將環繞'#all_locations'元素,而不是其內容。爲什麼不先將表追加到'#all_locations',然後將這些行附加到表中? – Blazemonger

+0

啊,你說得對。 –

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('')); 
+1

在一些瀏覽器,它甚至更快地建立一個字符串數組,它.append'ing到DOM之前'將它們連接起來的一次。 – Blazemonger

+0

您是否知道哪個瀏覽器在兩個流程中都更快? – Jasper

+0

我一直在試圖找到通過瀏覽器測量它的quirksmode文章,但不能。但是,IIRC大部分是舊式瀏覽器,但顯示出了改進。 – Blazemonger

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/