【发布时间】:2013-05-05 18:58:26
【问题描述】:
非常感谢您的阅读。
我有一个跨多个页面的分页数据集(从 SPRY XML 数据集创建)。
我使用 jquery cookies https://github.com/carhartl/jquery-cookie 来保存选中的复选框,因为选中的复选框在页面之间丢失了。我用过了
以下代码用于设置 cookie(来自 stackoverflow 帖子)
$(document).ready(function(){
// find the div named books containg rows and a checkbox in the end
$("#books").on("click",function(){
$(":checkbox:checked.chkbCsm").each(function() {//alert("test");
var mycookie = $.cookie($(this).attr('value'));
if (mycookie && mycookie == "true") {
$(this).prop('checked', mycookie);
}
});
$(":checkbox:checked.chkbCsm").change(function() {
$.cookie($(this).attr("value"), $(this).prop('checked'), {
path: '/',
expires: 365
})
});
});
包裹在 .on 中,因为表格是动态创建的。 cookie 设置正确。
我创建了以下 sn-p 来通过读取来自的值来恢复复选框 cookie 数组。
$(document).ready(function() {
var cookies = get_cookies_array();
var temp = [];
// keep only cookies relevant in temp
for( var name in cookies) {
if (!isNaN(name) && cookies[name]=="true") {
temp.push(name);
}
}
//restore all cookies from temp array
for( i=0 ; i<temp.length ; i++) {
var text=temp[i];
$('input[value='+text+']').prop('checked', true);
}
});//document ready
代码可以正常运行,但存在问题。
假设选中了一个复选框,设置了 cookie,然后您移至下一页,然后
你搬回来。
cookie 正确地恢复了复选框。但是如果你取消选中
复选框点击被忽略,cookie 仍然被认为包含一个选中的复选框。
如果您再次重复检查取消检查,则 cookie 正确设置为 false(即取消检查)。
这可能意味着第一次 .change() 函数没有被触发,这绝对是不需要的。
此外,我了解,如果
复选框以编程方式更改状态。change() 未被触发。
我尝试了几条路线(将 .triggerHandler("change"); 放在 .prop() 旁边)
并研究了Need checkbox change event to respond to change of checked state done programmatically 和Why isn't my checkbox change event triggered?,但没有解决我的问题。
欢迎任何想法如何解决这个问题。 非常感谢
【问题讨论】:
标签: jquery jquery-cookie