【发布时间】:2017-04-17 04:51:09
【问题描述】:
所以基本上,如果 DOM 中已经存在行,它们向上和向下移动行可以完美地工作,但是使用 jquery 附加行并尝试向上和向下移动它是行不通的。
$(".addmore").on('click',function(){
count=$('table tr').length;
var data="<tr><td>"+count+"</td>";
data+="<td><a class='down' href='#'>Down</a> <a class='up' href='#'>Up</a></td>";
$('table').append(data);
});
$(".up,.down").click(function () {
var $element = this;
var row = $($element).parents("tr:first");
if($(this).is('.up')){
row.insertBefore(row.prev());
}
else{
row.insertAfter(row.next());
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button type="button" class='addmore'>+ Add Row</button>
<table>
<thead>
<tr>
<th>ID</th>
<th>Action</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td><a class="down" href="#">Down</a> <a class="up" href="#">UP</a></td>
</tr>
</tbody>
</table>
请运行上面的示例,因为它会清楚地解释。
在此示例中,您可以看到行 ID 1 完美地上下移动,因为它已经存在于表中,但如果我添加更多行,则移动它们不起作用。
【问题讨论】:
标签: jquery