2012-08-12 63 views
0

我想通過jQuery動態添加表格行。一切正常,但行不會將自己添加到最後的< tr>。相反,它自身增加了<以上的表格> ...通過jQuery自動添加表格行

我很困惑。任何人都可以幫我嗎?下面是代碼

的Javascript

var counterx = 2; 
var counter = 2; 

$(document).ready(function(){ 
    $("#addMoreRcpt").click(function(){ 
     if (counterx>10){ 
      alert("Only 10 reciepients are allowed"); 
      return false; 
     } 

     var newTextBoxDiv = $(document.createElement('div')).attr("id", 'RcptEml_' + counter); 
     newTextBoxDiv.append("<tr><td>New Data</td><td>New Data</td><td>New Data</td></tr>"); 

     newTextBoxDiv.appendTo("#RcptGroup"); 
     counter++; 
     counterx++; 
    }); 
}); 

function fncDelRcpt(id){ 
    $("#RcptEml_"+id).remove(); 
    counterx--; 
} 

HTML

<table border=1> 
<div id="RcptGroup"> 
<tr> 
    <th>1</th> 
    <th>2</th> 
    <th>3</th> 
</tr> 
<div id="1"> 
<tr> 
    <td>data</td> 
    <td>Data</td> 
    <td>data</td> 
</tr> 
</div> 
</div> 

</table> 
<br /><a id="addMoreRcpt" href="#" >Add more reciepients</a> 
+4

你是否在'table'的'div'中包裝'tr'元素?這是無效的HTML,可能是你的問題的原因。 'div'可以出現在'th'或'td'裏面,但是'table'內的其他地方不會出現。 – 2012-08-12 23:12:00

+2

你的代碼在小提琴中:http://jsfiddle.net/userdude/2au73/ @DavidThomas也許是對的,至少聽取了他的建議。 – 2012-08-12 23:16:32

+0

是的,顯然jQuery的append()創建tbody標籤並在其中添加新行,而其他行仍保留在表中。如果你不想使用那個tbody,在這裏也使用基本的javascript:'document.getElementById('RcptGroup')。appendChild(newTextBoxDiv [0]);' – Stano 2012-08-12 23:26:48

回答

1

這裏的改變你的代碼的部分,應該工作:

腳本:

$(document).ready(function() { 
    $("#addMoreRcpt").click(function() { 
     if (counterx > 10) { 
      alert("Only 10 reciepients are allowed"); 
      return false; 
     } 
     var newTextBoxRow = $(document.createElement('tr')).attr("id", 'RcptEml_' + counter); 
     newTextBoxRow.append("<td>New Data</td><td>New Data</td><td>New Data</td>"); 
     newTextBoxRow.appendTo("#RcptGroup"); 
     counter++; 
     counterx++; 
    }); 
});​ 

表:

<table border="1" id="RcptGroup"> 
    <tr id="0"> 
     <th>1</th> 
     <th>2</th> 
     <th>3</th> 
    </tr> 
    <tr id="RcptEml_1"> 
     <td>data</td> 
     <td>Data</td> 
     <td>data</td> 
    </tr> 
</table>​​​​​​​​​​​​ 

工作小提琴:http://jsfiddle.net/pratik136/2au73/5/


正如在評論你的問題建議,<Div/> s不能嵌套在<Table/>秒。這裏有一個HTML 4.01的指南,但幾乎所有的應該仍然是這樣的:http://www.cs.tut.fi/~jkorpela/html/nesting.html

+0

這裏是rub:http://jsfiddle.net/userdude/2au73/2 /可點擊元素在哪裏? – 2012-08-12 23:22:11

+0

這裏有一個'click'元素? http://jsfiddle.net/2au73/6/ – undefined 2012-08-12 23:23:39

+0

@雷蒙森 - 你打我[[一拳](http://jsfiddle.net/userdude/2au73/4/)。 – 2012-08-12 23:24:36