考虑以下输入对
<input type="text" class="item_name" value="iphone">
<input type="text" class="item_qty" value="10">
<input type="text" class="item_name" value="macbook">
<input type="text" class="item_qty" value="5">
页面上输入对的数量是动态的,而不是固定的。
我希望遍历所有对并将值作为对存储,以便稍后输出到表格中。
我一直在尝试使用 jQuery 的 each()
来完成它,但我无法完全弄明白。
var detail = [];
//var detail = {};
$('input').each(function(index) {
detail[index] = $(this).val();
//detail.index = $(this).val();
});
console.log(detail);
这输出
["iphone", "10", "macbook", "5"]
这不是我需要的。
我习惯使用 PHP,那么在 JS/jQuery 中将输入对存储为多维关联数组/对象的正确方法是什么?
最佳答案
您可以遍历类 item_name
的元素并创建一个对象数组,每个对象都有一个 name
和 qty
属性(property)。
您可以使用 jQuery 的 .map()
更轻松地创建此数组:
var details = $('.item_name').map(function() {
return {
name: $(this).val(),
qty: $(this).next('.item_qty').val()
};
}).get();
console.log(details);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" class="item_name" value="iphone">
<input type="text" class="item_qty" value="10">
<input type="text" class="item_name" value="macbook">
<input type="text" class="item_qty" value="5">
关于javascript - 如何在 JS 中存储多组输入值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42195497/