我在我的 jQuery 代码中遇到了我认为的逻辑问题。我正在创建一个要 JSON.stringify 的对象数组并推送到 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));
}
});
});
如果这令人困惑,再次抱歉。我有一种感觉,我让这件事变得比它必须要复杂得多......
谢谢!