我有一个表,可以在其中选择/取消选择许多行。我想在表格中上下移动这些行。但是,当我移动这些行时,它们消失了,我也不知道为什么。我认为问题出在以下精确的代码行上:
$(this).appendTo($(this).prev());
$(document).ready(function() {
$("#table1 tbody tr").click(function() {
$(this).toggleClass('selected');
});
});
$(document).ready(function() {
$("#table2 tbody tr").click(function() {
$(this).toggleClass('selected');
});
});
$(document).ready(function() {
$(".down").click(function() {
$('#table1 tr').each(function() {
if ($(this).attr('class') == 'selected') {
$(this).appendTo($(this).next());
}
});
});
});
$(document).ready(function() {
$(".up").click(function() {
$('#table1 tr').each(function() {
if ($(this).attr('class') == 'selected') {
$(this).appendTo($(this).prev());
}
});
});
});
.selected td {
background: #ffffcf;
}
table {
width: 100%;
border-collapse: collapse;
}
td {
border: 1px solid #ddd;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button type="button" class="up">UP</button>
<button type="button" class="down">DOWN</button>
<h2>Table1</h2>
<table id="table1">
<tr>
<td>Row1</td>
</tr>
<tr>
<td>Row2</td>
</tr>
<tr>
<td>Row3</td>
</tr>
<tr>
<td>Row4</td>
</tr>
<tr>
<td>Row5</td>
</tr>
<tr>
<td>Row6</td>
</tr>
</table>
<h2>Table2</h2>
<table id="table2">
<tr>
<td>Row21</td>
</tr>
<tr>
<td>Row22</td>
</tr>
<tr>
<td>Row23</td>
</tr>
<tr>
<td>Row24</td>
</tr>
<tr>
<td>Row25</td>
</tr>
<tr>
<td>Row26</td>
</tr>
</table>
jsFiddle:https://jsfiddle.net/5jxvaw3d/
答案 0 :(得分:0)
只需将appendTo()
更改为insertBefore()
和insertAfter()
$(document).ready(function() {
$("#table1 tbody tr").click(function() {
$(this).toggleClass('selected');
});
});
$(document).ready(function() {
$("#table2 tbody tr").click(function() {
$(this).toggleClass('selected');
});
});
$(document).ready(function() {
$(".down").click(function() {
$('#table1 tr').each(function() {
if ($(this).attr('class') == 'selected') {
$(this).insertAfter($(this).nextAll(':not(.selected)').eq(0));
}
});
});
});
$(document).ready(function() {
$(".up").click(function() {
$('#table1 tr').each(function() {
if ($(this).attr('class') == 'selected') {
$(this).insertBefore($(this).prevAll(':not(.selected)').eq(0));
}
});
});
});
.selected {
background-color: #F00;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button type="button" class="up">UP</button>
<button type="button" class="down">DOWN</button>
<h2>Table1</h2>
<table id="table1">
<tr>
<td>Row1</td>
</tr>
<tr>
<td>Row2</td>
</tr>
<tr>
<td>Row3</td>
</tr>
<tr>
<td>Row4</td>
</tr>
<tr>
<td>Row5</td>
</tr>
<tr>
<td>Row6</td>
</tr>
</table>
<h2>Table2</h2>
<table id="table2">
<tr>
<td>Row21</td>
</tr>
<tr>
<td>Row22</td>
</tr>
<tr>
<td>Row23</td>
</tr>
<tr>
<td>Row24</td>
</tr>
<tr>
<td>Row25</td>
</tr>
<tr>
<td>Row26</td>
</tr>
</table>
修改
快速解决所选两个彼此相邻的问题
将此$(this).insertBofer($(this).prev());
更改为$(this).insertBefore($(this).prevAll(':not(.selected)').eq(0));
(更新的代码段)