jQuery:更改表两行的顺序
问题描述:
我想更改表中两行的顺序.
I want to change the order of two rows in a table.
我有此代码:
console.log(position.parent().parent().prev());
console.log(position.parent().parent());
//I expected this line do the work, but no...
$(this).parent().parent().prev().insertAfter($(this).parent().parent());
正在打印此:
<tr>
<td>Element 1</td>
<td>…</td>
<td>2008-02-02</td>
<td class="jander" data-pos="0" data-category="1">…</td>
</tr>
<tr>
<td>Element 2</td>
<td>…</td>
<td>2007-02-02</td>
<td class="jander" data-pos="1" data-category="1">…</td>
</tr>
有什么主意吗?
致谢
哈维
答
var row = $(this).closest('tr');
row.insertAfter( row.next() );
示例: http://jsfiddle.net/hkkKs/
取决于您要定位的对象.如果第一个具有点击处理程序,则需要上面的代码.
Depends on which one you're targeting. If the first one has the click handler, then you'd need the code above.
此外, closest()
[docs] 方法是定位祖先<tr>
的更安全方法.可能就是问题所在.
Also, the closest()
[docs] method is a safer way to target the ancestor <tr>
. That may have been the issue.
如果您希望以相反的方式使用它,则您的代码可以使用,但是再次使用.closest()
.
If you want it the opposite way, your code would work, but again, use .closest()
instead.
$('span').click(function() {
var row = $(this).closest('tr');
row.prev().insertAfter(row);
});