Javascript 更改表列顺序
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5464219/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Change table columns order
提问by Frayx
I need to change the order of columns in a table in html / js dynamically, you can tell me how to do it?
我需要动态更改html / js中表格中的列顺序,您可以告诉我该怎么做吗?
回答by Hux
If you only require to simply move a column without any fancy drag-drop animation, the following JS should do the trick:
如果你只需要简单地移动一列而不需要任何花哨的拖放动画,下面的 JS 应该可以做到:
<script type="text/javascript">
$(function() {
jQuery.each($("table tr"), function() {
$(this).children(":eq(1)").after($(this).children(":eq(0)"));
});
});
</script>
Replacing the numbers as necessary. The concept works
根据需要替换数字。这个概念有效
It seems that writing this as a one liner isn't really possible. including td in the selector, even with the row selector seems to hold each tdon a separate index, ignoring rows.
似乎将其写为单行是不可能的。在选择器中包含 td ,即使行选择器似乎将每个 td保存在单独的索引上,忽略行。
A jQuery grid plugin should do the trick otherwise. Although I have no experience with such plugins.
否则,jQuery 网格插件应该可以解决问题。虽然我没有使用此类插件的经验。
回答by typeof
Moving columns is not that hard:
移动列并不难:
You can use this function:
您可以使用此功能:
jQuery.moveColumn = function (table, from, to) {
var rows = jQuery('tr', table);
var cols;
rows.each(function() {
cols = jQuery(this).children('th, td');
cols.eq(from).detach().insertBefore(cols.eq(to));
});
}
Then invoke it like so:
然后像这样调用它:
var tbl = jQuery('table');
jQuery.moveColumn(tbl, 2, 0);
So, by knowing the index of the column, and the index of where you'd like to put it (zero-based), you can move the columns, including column headings.
因此,通过了解列的索引以及您想要放置它的位置的索引(从零开始),您可以移动列,包括列标题。
Here is the working jsfiddle: http://jsfiddle.net/Qsys7/1/
这是工作的 jsfiddle:http: //jsfiddle.net/Qsys7/1/
回答by mVChr
Here's a jQuery plugin I just wrote to switch the contents of two columns:
这是我刚刚编写的用于切换两列内容的 jQuery 插件:
$.fn.switchColumns = function ( col1, col2 ) {
var $this = this,
$tr = $this.find('tr');
$tr.each(function(i, ele){
var $ele = $(ele),
$td = $ele.find('td'),
$tdt;
$tdt = $td.eq( col1 ).clone();
$td.eq( col1 ).html( $td.eq( col2 ).html() );
$td.eq( col2 ).html( $tdt.html() );
});
};