0

我在我的 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));          
    }
 });
});

如果这令人困惑,再次抱歉。我有一种感觉,我让这件事变得比它必须要复杂得多......

谢谢!

4

1 回答 1

1

你有几个小错误。

这是一个工作代码的小提琴:http: //jsfiddle.net/ezanker/8q4ss/

在更改处理程序中,您应该每次都创建一个新的 init_char_object (var init_char_object = new Object();),然后在检查名称是否已经在数组中时,您需要在插入缺少的名称之前迭代整个数组。我使用了一个名为 foundInList 的布尔值,默认情况下它为 false,并且仅在找到名称时才设置为 true。然后在循环之外,如果该布尔值仍然为假,则可以插入名称。此外,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));          
});
于 2013-11-06T22:32:59.637 回答