2010-04-02 71 views
1

我添加了一个jquery函数,在我的表的最后动态添加一个<tr>。它工作正常,直到我添加表头到我的表。在我做完这些之后,该功能开始每次在表格中添加2个<tr>。发生了什么?使用jquery添加tr

HTML:

<table id="table" border="0"> 
<th>Col 1</th><th>Col2</th><th>col3</th> 
<tbody> 
<tr> 
    <td> 
     <select> 
      <option value ="one">one</option> 
      <option value="two">two</option> 
     </select> 
    </td> 
    <td> 
     <input type="text"></input> 
    </td> 
    <td> 
     <input type="text"></input> 
    </td> 
</tr> 
</tbody> 
</table> 

jQuery代码:

$(function(){ 
    $('a#add').click(function(){ 
    $('#table > tbody').append('<tr><td><select><option value ="one">one</option><option value="two">two</option></select></td><td><input type="text"></input></td><td><input type="text"></input></td></tr>'); 
    }); 

回答

3

浏览器会通过与其他TBODY周边的日,以弥补你的代码。尝试用thead围绕th的。

<table id="table" border="0"> 
    <thead> 
     <th>Col 1</th><th>Col2</th><th>col3</th> 
    </thead> 
    <tbody> 
     <tr> 
      <td> 
       <select> 
        <option value ="one">one</option> 
        <option value="two">two</option> 
       </select> 
      </td> 
      <td> 
       <input type="text"></input> 
      </td> 
      <td> 
       <input type="text"></input> 
      </td> 
     </tr> 
    </tbody> 
</table> 
+0

+1更多解释比我的答案;) – 2010-04-02 19:15:42

0

如果你要使用tbody,你需要使用thead为好。

0

添加:last你选择像这样(demosource):

$(function(){ 
    $('a#add').click(function(){ 
    $('#table > tbody:last').append('<tr><td><select><option value ="one">one</option><option value="two">two</option></select></td><td><input type="text"></input></td><td><input type="text"></input></td></tr>'); 
    return false; 
    }); 
}); 

由于标题还不的tbodythead部分时,浏览器会自动创建为他们tbody。因此你的渲染表有两个tbody s。 更好的解决方案是保持当前的选择和把一个报头的thead部分这样的:

<thead> 
<th>Col 1</th><th>Col2</th><th>col3</th> 
</thead> 

或者只是把它放在已有tbody这样浏览器就不会做一个新的。

0

从您的jQuery选择器中删除> tbody。在那之后它对我很好。

$('a#add').click(function(){ 
    $('#table').append('<tr><td><select><option value ="one">one</option><option value="two">two</option></select></td><td><input type="text"></input></td><td><input type="text"></input></td></tr>'); 
});