我遇到了我认为是jQuery代码中的逻辑问题。我正在创建一个JSON.stringify'd对象数组并推送到localStorage。格式如下:
arr = [{“name”:“Some Name”,“number”:“1”},{“name”:“Another Name”,“number”:“52”}等......
页面上有可变数量的滑块,每个滑块对应一个“名称”。并且滑块的值对应于“数字”。当滑块更新时,它应使用更新的数字更新相应的“名称”。
我无法解决这个问题。我可以让它做两件事之一:每次滑块移动时在数组中添加一个新对象。结果:[{“name”:“Some Name”,“number”:“1”},{“name”:“Some Name”,“number”:“2”},{“name”:“Some name “,”数字“:”3“}]
或者,如果我调整一下,我可以让它替换数字并保留名称......直到移动另一个滑块,此时它会擦除现有对象并用新对象替换它名称。
我想要的是在每个滑块的数组中有一个对象。由于滑块的数量会因某些设置而异,因此我无法对ID进行硬编码。
如果这听起来很复杂,我很抱歉。
这是我的代码:
$(document).on("change", ".init_slider", function() {
init_val = $(this).val();
char_name = $(this).parent().prev().prev().html();
init_char_object.name = char_name;
init_char_object.initroll = init_val;
// If the array is empty, push the object into the array
if (init_array.length === 0) {
init_array.push(init_char_object);
} else {
// Check the array for the current name. If it's already there, just replace the number.
// If it's not there, push the new object into the array.
$.each(init_array, function(i) {
if(init_array[i].name === char_name) {
init_array[i].initroll = init_val; // new add
return false;
} else {
init_array.push(init_char_object);
}
});
// Update localStorage with the array.
localStorage.setItem("_init_data", JSON.stringify(init_array));
}
});
});
如果这令人困惑,请再次抱歉。我有一种感觉,我要让它变得更加复杂......
谢谢!
答案 0 :(得分:1)
你有几个小错误。
以下是工作代码的小提琴: http://jsfiddle.net/ezanker/8q4ss/
在更改处理程序中,您应该每次都创建一个新的init_char_object(var init_char_object = new Object();)然后在检查名称是否已经在数组中时,您需要在插入缺失之前迭代整个数组名称。我使用了一个名为foundInList的布尔值,默认情况下为false,只有找到名称才设置为true。然后在循环外部,如果该布尔值仍为false,则可以插入名称。此外,localStorage.setItem应该在IF-ELSE之外:
var init_array = [];
$(document).on("change", ".init_slider", function() {
init_val = $(this).val();
char_name = $(this).parent().prev().html();
var init_char_object = new Object();
init_char_object.name = char_name;
init_char_object.initroll = init_val;
if (init_array.length === 0) {
init_array.push(init_char_object);
} else {
var foundInList = false;
$.each(init_array, function(i) {
if(init_array[i].name === char_name) {
init_array[i].initroll = init_val; // new add
foundInList = true;
return false;
}
});
if (!foundInList){
init_array.push(init_char_object);
}
}
localStorage.setItem("_init_data", JSON.stringify(init_array));
});