2014-01-15 66 views
0

不工作這是我的代碼,我正在撰寫一個表:jQuery的.append()根據需要

$("#results").append("<table><tr><th>Name</th><th>Phone Number</th></tr>"); 
$("#results").append("<tr><td>John</td><td>1231231234</td></tr>"); 
$("#results").append("</table>"); 

當我使用CSS應用邊框這個表,它不得到正確​​應用。
請參考這個小提琴:http://jsfiddle.net/23NQX/1/

我在做什麼錯在這裏?

+0

看看另這三行。沒有上下文,他們沒有意義。但他們是獨立執行的。 – Prinzhorn

+0

Append需要*元素*(將自動從HTML字符串創建) - 它不會*部分HTML片段,因爲它直接在DOM上工作。 – user2864740

回答

3

創建變量table ..追加<tr>吧...和追加最終table導致

試試這個

var table=$('<table>'); 
table.append('<tr><th>Name</th><th>Phone Number</th></tr>'); 
table.append("<tr><td>John</td><td>1231231234</td></tr>"); 

$("#results").append(table); 

更加清晰可讀。

追加不接受額外的參數,所以你甚至可以做

table.append('<tr><th>Name</th><th>Phone Number</th></tr>',"<tr><td>John</td><td>1231231234</td></tr>"); 

但我更喜歡去與第一...

fiddle

+2

這是做到這一點的正確方法。 – user1853181

1

追加未關閉的標籤將自動關閉標籤,如果你不親自關閉它們,所以在你的情況下,它會創建2個表。所以把字符串放在一起。

$("#results").append("<table><tr><th>Name</th><th>Phone Number</th></tr><tr><td>John</td><td>1231231234</td></tr></table>"); 

DEMO

-1
$("#results").append("<table id='my_table' border='1'><tr><th>Name</th><th>Phone Number</th></tr></table>"); 
$("#my_table").append("<tr><td>John</td><td>1231231234</td></tr>"); 
+0

它沒有工作。 http://jsfiddle.net/23NQX/3/ –

0

你必須首先創建表,然後將行附加到

像這樣:

$("#results").append("<table><tr><th>Name</th><th>Phone Number</th></tr></table>"); 
$("#results > table").append("<tr><td>John</td><td>1231231234</td></tr>"); 

退房this fiddle

0

你的第一個附加創建表,然後附加表

$("#results").append("<table><tr><th>Name</th><th>Phone Number</th></tr></table>"); 
$("#results").children("table").append("<tr><td>John</td><td>1231231234</td></tr>"); 
0

我總是覺得它有助於想到的事情反過來:

// create the table 
$("<table>") 
    // append the header 
    .append("<tr><th>Name</th><th>Phone Number</th></tr>") 
    // append a row to the table 
    .append("<tr><td>John</td><td>1231231234</td></tr>") 
    // append the table to the DOM 
    .appendTo($("#results")); 

Here's a fiddle顯示這個工程,因爲你想要的,並且更容易閱讀。

0

我給你使用一個結構:

$("#results").append($("<table>") 
       .append($("<tr>") 
        .append($("<th>").html("Name")) 
        .append($("<th>").html("Phone Number")) 
       ) 
       .append($("<tr>") 
        .append($("<td>").html("John")) 
        .append($("<td>").html("123123123")) 
       ) 

) 

可以很容易地修改和讀取。

DEMO:http://jsfiddle.net/23NQX/7/

0

一個簡單的方法

$("#results").append("<table id='table'><tr><th>Name</th><th>Phone Number</th</tr></table>"); 
$("#table tr:last").after("<tr><td>John</td><td>1231231234</td></tr>");