gpt4 book ai didi

javascript - 遍历 HTML 元素

转载 作者:行者123 更新时间:2023-11-29 17:48:39 25 4
gpt4 key购买 nike

我有以下 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:Working js fiddle

关于javascript - 遍历 HTML 元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46318574/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com