无法使用 jquery.cookie 保留复选框值 [英] Cannot retain checkbox value using jquery.cookie
问题描述
我使用 jQuery DataTable
工具栏上有一个 checkbox
用于检索或不检索所有记录.由于 DataTable
的 stateSave 功能无法正常工作,我尝试使用jquery.cookie 以保留复选框重新加载 DataTable
后的值(因为每次重新加载时都会动态重新绘制复选框),如下所示:
I use jQuery DataTable
and there is a checkbox
on the toolbar that is used for retrieving all records or not. As stateSave feature of DataTable
does not work properly, I tried to use jquery.cookie in order to keep the checkbox value after reloading the DataTable
(because the checkbox is redrawn dynamically on every reload) as shown below:
$(document).ready(function() {
$('#example').DataTable( {
//code omitted for brevity
"serverSide": true,
"ajaxSource": "/Student/GetStudents",
"fnServerData": function (sSource, aoData, fnCallback) {
/* Add some extra data to the sender */
aoData.push({ "name": "isAll", "value": $("#cbIsAll").is(":checked") });
$.getJSON(sSource, aoData, function (json) {
/* Do whatever additional processing you want on the callback, then tell DataTables */
fnCallback(json);
});
},
"fnDrawCallback": function() {
$("div.toolbar").html('<input type="checkbox" id="cbIsAll" name="demo" /> Get all records');
}
});
$(document).on('change', '#cbIsAll', function () {
var isClicked = $('#cbIsAll').is(':checked') ? true : false;
$.cookie('clicked', isClicked, { expires: 1 }); // expires in 1 day
table.ajax.reload();
$('#cbIsAll')[0].checked = ($.cookie('clicked') == "true") ? true : false;
});
});
在调试代码后,我看到虽然 $('#cbIsAll')[0].checked
行正确执行为 true,但 checkbox
稍后丢失了值比这条线.你能澄清一下错误在哪里吗?或者有没有更好更聪明的方法来保持 checkbox
值?
After debugging the code I saw that although the $('#cbIsAll')[0].checked
line is executed properly as true, the checkbox
lost value later than this line. Could you please clarify me about where the mistake is? Or is there a better and smart way to keep the checkbox
value?
推荐答案
没有理由在您的情况下使用 $.cookie
.在复选框 change
事件中,您可以简单地存储选中状态的值,并使用它来设置重新加载表格时生成的新复选框的 checked
属性>
There is no reason to use $.cookie
in your case. In the checkbox change
event, you can simply store the value of the checked state and use that to set the checked
property of the new checkbox generated when you reload the table
var isChecked;
$(document).on('change', '#cbIsAll', function () {
// Store the current value
isChecked = $(this).is(':checked');
....
然后在datatable的回调函数中,设置checkbox的选中状态
Then in the datatable's callback function, set the checked state of the checkbox
$('#cbIsAll').prop('checked', isChecked);
这篇关于无法使用 jquery.cookie 保留复选框值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!