我一直在网上寻求帮助,但是并没有取得太大的成功。很多人建议使用插件/ widgets,但是对于如何使用我发现的插件并没有明确的说明,并且所有演示都已被删除。
有人可以协助您如何使表格的列可排序,方法与表格行相同吗?我想要做的就是通过拖动标题对表列进行排序。它们不需要是永久的,可以回到页面刷新的状态。
如果jQuery不是解决此问题的最佳方法,那么我愿意接受其他方法。
编辑:我在这里找到了解决方案:http://jebaird.com/2010/12/29/dragtable-a-jquery-ui-widget-to-re-arrange-table-columns-via-drag-and-drop.html
答案 0 :(得分:0)
要对表列进行排序,建议您使用数据表。
这是一个jQuery插件,它支持许多功能,包括排序。
数据表的各种功能是:
要查看示例,请参考以下链接:https://datatables.net/examples/basic_init/table_sorting.html
将以下JavaScript文件添加到您的项目中以运行示例:
https://code.jquery.com/jquery-3.3.1.js
https://cdn.datatables.net/1.10.19/js/jquery.dataTables.min.js
如果您有一个包含五列的表格,并且希望对第三列进行排序,则可以使用:
$(document).ready(function() {
$('#example').DataTable( {
"order": [[ 3, "desc" ]]
} );
} );
为CSS添加以下内容:https://cdn.datatables.net/1.10.19/css/jquery.dataTables.min.css
答案 1 :(得分:0)
尝试遵循我在项目中使用过的内容
没有任何插件
$(document).on('click','#combinationload tr:not(:first)',function(){
$('#combinationload tr').removeClass('Selected')
$(this).addClass('Selected');
});
$(document).on('click', '#btnShiftUp', function () {
debugger
var ShiftingRows = $('#combinationload tr');
var currentPosition = '';
var CurrentTR = '';
var selectedClass = '';
$.each(ShiftingRows, function (l, ROW) {
if ($(ROW).hasClass('Selected')) {
currentPosition = l;
CurrentTR = ROW.outerHTML;
selectedClass = true;
return false;
}
});
if(currentPosition!=1)
{
if (selectedClass) {
if (currentPosition > 0 && selectedClass) {
$('#combinationload > tbody > tr').eq(currentPosition).remove();
$('#combinationload > tbody > tr').eq(currentPosition - 1).before(CurrentTR);
}
}
}
else if (!selectedClass) {
alert('Select Row For changing Place')
}
});
$(document).on('click', '#btnShiftDown', function () {
var ShiftingRows = $('#combinationload tr');
var currentPosition = '';
var CurrentTR = '';
var classount = false;
$.each(ShiftingRows, function (l, ROW) {
if ($(ROW).hasClass('Selected')) {
currentPosition = l;
CurrentTR = ROW.outerHTML;
classount = true;
return false;
}
});
if (currentPosition != ShiftingRows.length - 1 && classount) {
$('#combinationload > tbody > tr').eq(currentPosition).remove();
$('#combinationload > tbody > tr').eq(currentPosition).after(CurrentTR);
}
else if (!classount) {
alert('Select Row For changing Place');
}
});
.Selected{
background-color:#4caf50
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="combinationload" border="1">
<tr>
<th>Name</th>
<th>Favorite Color</th>
</tr>
<tr>
<td>Bob</td>
<td>Yellow</td>
</tr>
<tr>
<td>Two</td>
<td>2</td>
</tr>
<tr>
<td>Michelle</td>
<td>Purple</td>
</tr>
<tr>
<td>Four</td>
<td>4</td>
</tr>
</table>
<br/>
<br/>
<input type="button" id="btnShiftUp" value="UP" />
<input type="button" id="btnShiftDown" value="Down" />
答案 2 :(得分:0)
这是我用来解决此问题的方法。这不是最好的解决方案,但它起作用了: