2012-05-29 68 views
6

我正在尝试添加新行,即当前行的克隆。我试过下面的代码。它不会弹出错误,但不会添加行。我的代码在这里有什么错误?有没有其他简单的想法?在使用jQuery的当前行之后添加新表格行

 $('input[name="cmdAddRow"]').live('click', function(){ 
      $curRow = $(this).parent('tr'); 
      $newRow = $curRow.clone(true); 
      console.log($newRow); 
      $curRow.after($newRow); 
      console.log('added'); 
     }); 

HTML布局:

<table> 
    <tr> 
     <td><input type="hidden" name="uin" value="xxx"></td> 
     <td><input type="text" name="uname" value=""></td> 
     <td><input type="text" name="uadd" value=""></td> 
     <td><input type="text" name="utel" value=""></td> 
     <td><input type="button" name="cmdAddRow" value="Add"></td> 
    </tr> 
</table> 
+1

请加上你r问题的标记。 – VisioN

+0

你现在在里面生活吗?提及你的jquery版本。 –

+0

是的,我正在得到更改msg被添加到控制台正在写入 – KoolKabin

回答

13

$(this).parent('tr')找不到任何东西。您的input元素将位于tdth之内。 parent仅查找元素的直接父级,然后将其与您提供的选择器进行比较。因此它将找不到任何东西。然后你什么都不克隆,并且在没有任何东西之后插入新的东西。也许毫不奇怪,这实际上并没有做任何事情。

您需要使用closest,其寻找最近的元素

var $curRow = $(this).closest('tr'); 

还要注意搭配选择您正在使用全局变量,因为你不使用var(我在该行纠正此之上),你可能不想这样做。此外,live不是一个好用的功能;使用on来代替,该做同样的事情更优雅:

$('#yourTable').on('click', 'input[name="cmdAddRow"]', function() { 
    var $curRow = $(this).closest('tr'), 
     $newRow = $curRow.clone(true); 
    console.log($newRow); 
    $curRow.after($newRow); 
    console.log('added'); 
}); 
0

使用on代替livelive被废弃了,因为jQuery的最新版本,您parent()选择td元素,使用2种parent()方法或closest('tr')

$('input[name="cmdAddRow"]').on('click', function(){ 
      $curRow = $(this).parent().parent(); 
      $newRow = $curRow.clone(true); 
      console.log($newRow); 
      $curRow.after($newRow); 
      console.log('added'); 
}); 

http://jsfiddle.net/qVm75/3/

1

您可以选择使用$.closest$.parents,而不是$.parent这样

$('input[name="cmdAddRow"]').live('click', function(){ 
     $curRow = $(this).closest('tr'); 
     $newRow = $curRow.clone(true); 
     console.log($newRow); 
     $curRow.after($newRow); 
     console.log('added'); 
    });​ 

Working Fiddle

而且你应该考虑使用$.on因为$ .live现在折旧

+0

thnx你的代码也可以正常工作......但你错过了1分... – KoolKabin

相关问题