[英]Looping through html elements with the same class and finding the order of elements
[英]Looping through HTML elements
我有以下HTML / Bootstrap表單(動態生成):
<div id="date_fields">
<div class="form-group removeclass0">
<div class="col-sm-6 nopadding">
<div class="form-group">
<input type="text" class="form-control dateKey" name="dateKey[]" value="revision">
</div>
</div>
<div class="col-sm-6 nopadding">
<div class="form-group">
<div class="input-group">
<input type="text" class="form-control dateValue" name="dateValue[]" value="2010-09-20">
<div class="input-group-btn">
<button class="btn btn-danger" type="button" onclick="remove_date_fields(0);">
<span class="glyphicon glyphicon-minus" aria-hidden="true"></span>
</button>
</div>
</div>
</div>
</div>
<div class="clear"></div>
</div>
<div class="form-group removeclass1">
<div class="col-sm-6 nopadding">
<div class="form-group">
<input type="text" class="form-control dateKey" name="dateKey[]" value="publication">
</div>
</div>
<div class="col-sm-6 nopadding">
<div class="form-group">
<div class="input-group">
<input type="text" class="form-control dateValue" name="dateValue[]" value="2008-05-21">
<div class="input-group-btn">
<button class="btn btn-danger" type="button" onclick="remove_date_fields(1);">
<span class="glyphicon glyphicon-minus" aria-hidden="true"></span>
</button>
</div>
</div>
</div>
</div>
<div class="clear"></div>
</div>
這是JSFiddle: https ://jsfiddle.net/mleontenko/mmk9zo4L/
我需要遍歷這種形式並將dateKey和dateValue對存儲到一個看起來像這樣的數組中:
[
{
"dateKey":"revision",
"dateValue":"2010-09-20"
},
{
"dateKey":"publication",
"dateValue":"2008-05-21"
}
]
使用jQuery或純JavaScript的最佳方法是什么?
$( document ).ready(function() {
var keys = [];
var values = [];
var res = [];
$.each($("#date_fields").find(".dateKey"), function(i, key) {
keys[i] = $(".dateKey:eq("+i+")").val();
});
$.each($("#date_fields").find(".dateValue"), function(i, value) {
values[i] = $(".dateValue:eq("+i+")").val();
});
$.each($("#date_fields").find(".dateValue"), function(i) {
res[i] = {"dateKey" : keys[i], "dateValue": values[i]};
});
$("#result").text(JSON.stringify(res));
});
JSFiddle: 工作的js小提琴
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.