0

jQuery コードでロジックの問題と思われる問題が発生しています。オブジェクトの配列を作成して JSON.stringify し、localStorage にプッシュします。フォーマットは次のようになります。

arr = [{"name": "ある名前", "number": "1"},{"name": "別の名前", "number":"52"}, etc...

ページにはさまざまな数のスライダーがあり、各スライダーは「名前」に対応しています。そして、スライダーの値は「数値」に対応しています。スライダーが更新されると、適切な「名前」が更新された番号で更新されます。

これを機能させるのに問題があります。スライダーが動くたびに新しいオブジェクトを配列に追加します。結果: [{"name": "ある名前", "number": "1"},{"name": "ある名前", "number": "2"},{"name": "ある名前" ", "数値": "3"}]

または、微調整すると、番号だけを置き換えて名前を残すことができます... 別のスライダーが移動されるまで、その時点で既存のオブジェクトが消去され、新しい名前を使用して新しいオブジェクトに置き換えられます。

私が望むのは、各スライダーの配列に 1 つのオブジェクトを含めることです。スライダーの数は設定によって異なるため、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