我从之前关于如何在localstorage中存储页面上所有复选框的选中/未选中状态的问题中提取了以下代码片段:
$(function(){
var test = localStorage.input === 'true'? true: false;
$('[type="checkbox"]').prop('checked', test || false);
});
$('[type="checkbox"]').on('change', function() {
localStorage.input = $(this).is(':checked');
console.log($(this).is(':checked'));
});
当我选中其中一个复选框然后刷新页面时,一旦它重新加载,每个单个复选框都被选中。
我如何让这个存储每个单独的选中状态?
注我可能有0 - 50之间可用的复选框取决于有多少优秀的记录有在我的gridview,所以我没有固定的输入id的使用记录id关联到每一行。
如果您想依赖localStorage解决方案,您可以这样做:
$(function(){
$('[type="checkbox"]').each(function () {
var $this = $(this),
name = $this.attr('name');
$this.prop('checked', localStorage[name] === 'true');
});
});
$('[type="checkbox"]').on('change', function() {
var $this = $(this),
name = $this.attr('name');
localStorage[name] = $this.is(':checked');
});
http://jsfiddle.net/mct7xgq2/第一部分在页面加载时执行,并根据localStorage[name]值设置检查状态,其中name是输入的name属性。
第二部分在任何复选框被更改时执行:它像以前一样获取输入的名称,但不是读取值,而是写入值。
如果页面无法加载,最好将值存储在JS
对象中,而不是使用localStorage
。
只需要创建一个JS对象,并不断向其中推送值并存储
客户端解决方案如果页面不重新加载
$(function(){
var checkedItems ={};
$('[type="checkbox"]').on('change', function() {
//Store the ID value also in the localstorage
if($(this).is(':checked')){
var id = $(this).attr('id'); //Get the id if this is checked
checkedItems['id_'+id] = id;
}
});
});
如果页面重新加载,那么你最好的选择是使用服务器端概念,如Session
。每次选中一个特定的复选框时发送一个AJAX
请求,并将其存储在会话中。
服务器端解决方案
$(function(){
$('[type="checkbox"]').on('change', function() {
//Store the ID value also in the localstorage
if($(this).is(':checked')){
var id = $(this).attr('id'); //Get the id if this is checked
$.ajax({
type: 'POST',
url: your server side url path, //store it in a session
data: {'id':id},
dataType: 'html',
success: function(result){
//so some functionality
}
});
}
});
});
查看FIDDLE LINK
这是d3.js使用三元运算符的解决方案。它将此复选框的id与localStorage中key=id下存储的值进行比较。如果值为"true",则'this。Checked属性设置为true,否则设置为null (null表示没有Checked属性)
var box = d3.selectAll(".box").each(function(){
var id = this.id;
var storageValue = localStorage.getItem(id);
this.checked = storageValue === "true" ? true : null;
});
以前我有setItem在localStorage。复选框是动态创建的,附加到表
中的行。 rows.append('input')
.attr('type','checkbox')
,它又基于来自cvs的数据。复选框的id如下:
.attr("id", function(d,i) { return 'box'+' '+i; })
和复选框状态的'change':
d3.selectAll(".box").on("change", function() {
var id = this.id;
if ( this.checked ){
localStorage.setItem(id, this.checked);
}
else {
localStorage.removeItem(id);
}
});
我有数千行,每一行都有一个复选框。我在时间线检查中没有发现重大问题。所以我想这是一个很好的解。我不是d3.js专家。