2017-09-05 35 views
1

我正在使用.each循環遍歷一些div元素並獲取其中包含的某些輸入框的值。每個div代表一行,並且有一個Id來表示這個,即plot1, plot2...。我想將所有這些數據存儲在一個數組中,但我不知道如何構造它。給你舉個例子,我的意思是一些代碼。如何在使用jQuery的.each循環中構造一個數組?

有兩個div代表行,每行有兩個輸入字段。

<div class="coords"> 
    <div id="plot1" class="plotrow"> 
     <div class="lat"> 
      <input type="text" id="plot1_lat" value="1234" /> 
     </div> 
     <div class="long"> 
      <input type="text" id="plot1_long" value="4567" /> 
     </div> 
    </div> 
    <div id="plot2" class="plotrow"> 
     <div class="lat"> 
      <input type="text" id="plot2_lat" value="6984" /> 
     </div> 
     <div class="long"> 
      <input type="text" id="plot2_long" value="2348" /> 
     </div> 
    </div> 
    <button type="button" id="go">Go!</button> 
</div> 

使用jQuery我想遍歷這些div並使用以下格式將數據存儲在數組中。

{ "<value from div id>": [{ 
    "lat" : <<value from input>> 
    }, { 
    "long" : <<value from input>> 
    } 
]}; 

這裏是我的功能,當你在buttonw單擊第i個go

$('#go').on('click', function() { 
     var object = {}; 
     var array = []; 

     $('.coords input:text').each(function() { 

      var someArray = { 
       "plot": [{ 
        "lat": this.value 
       }, { 
        "long": this.value 
       }] 
      }; 
      array.push(someArray); 
     }); 
    }); 

一個id這是觸發我在陣列結構有點困惑所以我把一些虛擬值但是「plot」應該是來自div行的id,並且latlong應該是每個div行內的兩個輸入的值。

此外,我發現,因爲它坐在.each循環內,它將創建四個數組(每個輸入一個)而不是一個數組,其中所有輸入都由div id組織。

我希望這是有道理的,任何人都可以提供一些建議?

+0

是否有任何理由爲什麼你要在對象數組中存儲緯度和長度?您可以直接將它們直接存儲爲劇情對象的鍵。 – Terry

回答

2

達到你需要,你可以使用map()從HTML結構建立一個數組,像這樣的內容:

var arr = $('.plotrow').map(function() { 
 
    var o = {}; 
 
    o[this.id] = [ 
 
    { lat: $(this).find('.lat input').val() }, 
 
    { long: $(this).find('.long input').val() } 
 
    ] 
 
    return o; 
 
}).get(); 
 

 
console.log(arr);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<div class="coords"> 
 
    <div id="plot1" class="plotrow"> 
 
    <div class="lat"> 
 
     <input type="text" id="plot1_lat" value="1234" /> 
 
    </div> 
 
    <div class="long"> 
 
     <input type="text" id="plot1_long" value="4567" /> 
 
    </div> 
 
    </div> 
 
    <div id="plot2" class="plotrow"> 
 
    <div class="lat"> 
 
     <input type="text" id="plot2_lat" value="6984" /> 
 
    </div> 
 
    <div class="long"> 
 
     <input type="text" id="plot2_long" value="2348" /> 
 
    </div> 
 
    </div> 
 
    <button type="button" id="go">Go!</button> 
 
</div>

我假設你正在構建的對象結構一些外部插件需要它,因爲在給定HTML結構的情況下它可以被簡化。

相關問題