簡體   English   中英

將鍵值對存儲在數組中

[英]Storing key value pair in array

這是我的 html 輸入元素

<div class="form-group">
  <div class="col-lg-6">
     <input type="text" name="Key" class="form-control" placeholder="Key">
  </div>
  <div class="col-lg-6">
    <input type="text" name="Value" class="form-control" placeholder="Value"/>
  </div>
</div>

<div class="form-group">
  <div class="col-lg-6">
     <input type="text" name="Key" class="form-control" placeholder="Key">
  </div>
  <div class="col-lg-6">
    <input type="text" name="Value" class="form-control" placeholder="Value"/>
  </div>
</div>

如何獲取所有“鍵”和“值”對並使用 Jquery 將它們保存到數組? 像這樣的result =[ {'Key' : 'Value'}, {'Key' : 'Value'} ];

我自己正在學習 javascript 和 jQuery,但是由於您還沒有展示任何具體的嘗試並獲得解決方案,我可以描述如何去做我認為您想做的事情。 我的工作基於我已經在 jQuery 中看到的內容,與訪問該站點的很多人相比並不多,並且我自己做了一些谷歌搜索以確認一些事情。 也就是說,這里是我認為如何達到您想要的結果的描述。

這是一個文本示例,可幫助您完成示例。 由於您在 div 中的每對輸入都具有一致的類名,因此您可以使用$(".form-group")查找該類的所有元素。 一旦你有了你的配對數組,你就可以將事情提升到一個新的水平。 接下來,您可以使用 jQuery 的each()函數來迭代數組的內容。 對於數組的每個元素,您可以使用 find() 函數查找名稱為“Key”和“Value”的輸入。 此時,您可以填充 JSON 數組。

我已經讓你成為一個基本的小提琴

所以基本上使用 jQuery 的each()函數,您可以遍歷表單組並獲取鍵和值並將它們推送到您的數組中。

 //defining your empty array here var arr = []; //setting up the click function to return your array in console. $('.cnsllog').on('click', function() { //go through all the form groups $('.form-group').each(function() { //set the input with name equal to value as value variable value = $(this).find("input[name='Value']").val() //set the input with name equal to Keyas value Key key = $(this).find("input[name='Key']").val() //push these two variables to your array arr.push({ key: key, value: value }) }); console.log(arr) })
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.2/jquery.min.js"></script> <div class="form-group"> <div class="col-lg-6"> <input type="text" name="Key" class="form-control" placeholder="Key"> </div> <div class="col-lg-6"> <input type="text" name="Value" class="form-control" placeholder="Value" /> </div> </div> <div class="form-group"> <div class="col-lg-6"> <input type="text" name="Key" class="form-control" placeholder="Key"> </div> <div class="col-lg-6"> <input type="text" name="Value" class="form-control" placeholder="Value" /> </div> </div> <button class="cnsllog">put the array in console</button>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM