使用jquery在指定行之后插入一行

时间:2011-11-07 15:51:52

标签: jquery

我见过类似的例子,但没看到我正在寻找的东西 我已经根据一天中的时间创建了一个调度系统 这意味着我有24行 每行的第一个td都有一个“go”类的按钮 我正在尝试创建一个片段...当单击某个特定行上的单个按钮时,该行被克隆并插入到表格的下一行。
 我用一个按钮完成了这个,并使用了insertAfter对象  我假设我必须对.each做一些事情,但我不太熟悉它 这是一个尝试的例子 请注意,在这种情况下,我使用了go的id,我创建了一个隐藏的tr,其id为to_be_cloned,并在第1行后插入。
我需要能够在单击该行按钮后在任何其他行之后插入行。 (如果这有意义的话)

$("#go").click(function() { 
    $("#to_be_cloned").clone().show().attr('id','').insertAfter("#1");
})

3 个答案:

答案 0 :(得分:2)

使所有行具有相同的类。然后你可以试试这个:

$(".rowClass .go").live('click', function() {  //clicked go in this row
    var row = $(this).parents(".rowClass");
    row.clone().show().insertAfter(row);
});

小提琴:http://jsfiddle.net/maniator/E4K39/

答案 1 :(得分:2)

使用类将事件绑定到按钮而不是id。 如果您还有重复的ID,则无效,ID无法以数值开头。

<table>
   <tr>
      <td><input type="button" class="insertButton" value="Go"/></td>
      <td>Hello World</td>
   </tr>
</table>


$(document).ready(function(){
   $('.insertButton').live('click', function(){
       var row = $(this).closest('tr').clone();
       $(this).closest('table').append(row);
   });
});

jsFiddle Example

答案 2 :(得分:1)

JS:

$(".go").live('click', function() { 
    var $tr = $(this).closest('tr');
    $tr.clone().insertAfter($tr);
});

HTML:

<table>
    <tr>
        <td><a href="#" class="go">Go</a></td>
        <td>somethign</td>
        <td>another 1</td>
    </tr>
    <tr>
        <td><a href="#" class="go">Go</a></td>
        <td>somethign</td>
        <td>another 2</td>
    </tr>
    <tr>
        <td><a href="#" class="go">Go</a></td>
        <td>somethign</td>
        <td>another 3</td>
    </tr>
</table>

jsfddle:http://jsfiddle.net/jYMmu/4/