我有一个数据表,可以使用复选框过滤其列。选中复选框时显示列,如果未选中则隐藏列。我试图在页面刷新时保存复选框的状态(即选中或未选中),这确实有效(即,在刷新时仍选中已选中的框,未选中的框不选中)。不幸的是,这似乎对是否显示列没有影响。因此,如果单击复选框,则会显示该列,如果再次单击(未选中),则不会显示该列。刷新后,复选框状态相同,但列不再受到影响。我不仅要弄清楚如何保存复选框的状态,还要弄清楚这些复选框在页面刷新时所具有的效果(是否显示列)。
这是复选框的样子(请注意,我已在复选框中添加了选中以显示数据表的默认行为):
<label for="address" class="label">Name
<input class="box" type="checkbox" name="pname" id="pname" onclick="fnShowHide(0);" checked>
</label>
<label for="address" class="label">Address
<input class="box" type="checkbox" name="address" id="address" onclick="fnShowHide(1);" checked>
</label>
<label for="address" class="label">City
<input class="box" type="checkbox" name="city" id="city" onclick="fnShowHide(2);" checked>
</label>
<label for="address" class="label">State
<input class="box" type="checkbox" name="state" id="state" onclick="fnShowHide(3);" checked>
</label>
<label for="address" class="label">DOB
<input class="box" type="checkbox" name="dob" id="dob" onclick="fnShowHide(4);" checked>
</label>
<label for="address" class="label">Occupation
<input class="box" type="checkbox" name="occupation" id="occupation" onclick="fnShowHide(5);">
</label>
<label for="address" class="label">Vehicle Type
<input class="box" type="checkbox" name="vehicle_type" id="vehicle_type" onclick="fnShowHide(6);" checked>
</label>
这是数据表的样子(使用 ShowHide 函数):
var table = $('#people');
table.dataTable({
"iDisplayLength": 500,
"bPaginate": false,
"aLengthMenu": [[-1, 25, 50, 100], ["All", 25, 50, 100]],
'aoColumns': [
/* Name */ null,
/* Address */ null,
/* City */ null,
/* State */ null,
/* DOB */ { "bSortable": false },
/* Occupation */ { "bVisible": false },
/* Vehicle Type */ { "bVisible": false }
],
'sPaginationType': 'full_numbers',
'sDom': '<"dataTables_header"lfr>t<"dataTables_footer"ip>',
'fnInitComplete': function( oSettings )
{
table.closest('.dataTables_wrapper').find('.dataTables_length select').addClass('select blue-gradient glossy').styleSelect();
tableStyled = true;
}
});
function fnShowHide( iCol )
{
/* Get the DataTables object again - this is not a recreation, just a get of the object */
var oTable = $('#people').dataTable();
var bVis = oTable.fnSettings().aoColumns[iCol].bVisible;
oTable.fnSetColumnVis( iCol, bVis ? false : true );
}
这是我用来保持复选框状态的功能:
$("input.box").each(function() {
var mycookie = $.cookie($(this).attr('name'));
if (mycookie && mycookie == "true") {
$(this).prop('checked', mycookie);
}
});
$("input.box").change(function() {
$.cookie($(this).attr("name"), $(this).prop('checked'), {
path: '/',
expires: 365
});
});