【发布时间】:2015-11-15 06:12:13
【问题描述】:
我开发了这段简洁的代码,它给出了一个元素和一个格式正确的表格,在元素上创建了一个下拉菜单,允许用户切换列的视图。
我无法弄清楚如何使更改(哪些列保持隐藏)在页面更改时保持不变,因为在页面上放置一个带有分页的表格是一种常见的模式。
小提琴: https://jsfiddle.net/mssrq8ah/
我的 html 标记:
<table id="table">
<thead>
<tr>
<th>h1</th><th>h2</th><th>h3</th>
</tr>
</thead>
<tbody>
<tr>
<td>a1</td><td>a2</td><td>a3</td>
</tr>
<tr>
<td>b1</td><td>b2</td><td>b3</td>
</tr>
</tbody>
</table>
<button id="list">drop</button>
我的js函数:
table_hide("#list","#table")
function table_hide( button , table)
{
jQuery(button).attr("data-toggle","dropdown");
jQuery(button).addClass("dropdown-toggle");
jQuery(button).wrap("<div class='btn-group'>");
var list = "";
jQuery("thead").find("tr").first().find("th").each(function(index,element){
list = list + "<li>" +
"<div class='checkbox col-md-6'><label><input type='checkbox' checked value='"+index+"' class='td_hide'>"+jQuery(element).text()+"</label></div>"+
"</li>";
});
jQuery(button).after("<ul class='dropdown-menu col-md-12'>"+list+"</ul>");
jQuery(".td_hide").on("click",function(){
var target_column = jQuery(this).val();
jQuery("tr").each(function(index , element){
jQuery(this).find("th , td").eq(target_column).toggle();
});
});
jQuery(".dropdown-menu").find("select , .ws-popover-opener , .step-control").on("click",function(e){
e.stopPropagation();
});
}
如果可能的话,我想避免更多需要的库,因为我打算在 CMS 上使用它,而 jQuery/bootstrap 是这些天的标准。
【问题讨论】:
-
how to make the changes (which columns to stay hidden) persists on page change... 如果您对持久化任何内容感兴趣,您需要考虑使用本地存储、cookie 或数据库。当你刷新页面时,所有的JS数据都会丢失 -
我建议您将所有列的状态(可见或不可见)保存在 localStorage 中,并在页面加载后从该 localStorage 中读取并设置可见性。 localStorage 易于使用 - 只需执行 localStorage.setItem 和 localStorage.getItem。您可以通过执行 jQuery("tr").first().find('th, td').is(':visible') 来获取列的当前状态
-
非常感谢大家,我在我的最终解决方案下面发布了
标签: javascript jquery cookies twitter-bootstrap-3 html-table