我正在尝试在本地存储中保存多个选择值,并且数据正在设置并从本地存储中成功进入,但jquery不会检查该框。
以下是我的代码的fiddle
,下面是我正在使用的jquery代码:
$('.cmn').on('click', function() {
var fav, favs = [];
$('.cmn').each(function() { // run through each of the checkboxes
fav = {class: $(this).attr('class'), value: $(this).prop('checked')};
//console.debug(fav);
favs.push(fav);
});
localStorage.setItem("payment", JSON.stringify(favs));
});
$(document).ready(function() {
var payment = JSON.parse(localStorage.getItem('payment'));
if (!payment.length) {return};
//console.debug(payment);
for (var i=0; i<payment.length; i++) {
console.debug(payment[i]);
//alert("."+payment[i].class);
$("."+payment[i].class).prop('checked', payment[i].value);
}
});
答案 0 :(得分:3)
<强> Working fiddle 强>
您应该在i
中添加索引:eq()
以指定元素的索引,因为所有元素都具有相同的类cmn
:
$("."+payment[i].class+':eq('+i+')').prop('checked', payment[i].value);
希望这有帮助。
答案 1 :(得分:2)
添加计数器变量以跟踪您要定位的复选框
$('.cmn').on('click', function() {
var fav, favs = [], i=0;
$('.cmn').each(function() { // run through each of the checkboxes
fav = {class: $(this).attr('class'), value: $(this).prop('checked'), index: (i++)};
//console.debug(fav);
favs.push(fav);
});
localStorage.setItem("payment", JSON.stringify(favs));
});
$(document).ready(function() {
var payment = JSON.parse(localStorage.getItem('payment'));
if (!payment.length) {return};
//console.debug(payment);
for (var i=0; i<payment.length; i++) {
//console.debug(payment[i]);
//alert("."+payment[i].class);
$(".cmn:eq("+payment[i].index+")").prop('checked', payment[i].value);
}
});