jQuery从输入中获取值并创建一个数组
问题描述:
我在页面上有很多输入。我想使用jQuery为每个输入的名称和值创建一个关联数组。我试过了:
I have many inputs on a page. I want to create an associative array with each input's name and value using jQuery. I've tried:
<input class="activeInput" type="text" name="key1" value="red">
<input class="activeInput" type="text" name="key3" value="France">
inputValues = $('.activeInput').val();
编辑 - 感谢富有洞察力的评论,似乎创建一个对象是一种更好的方法。有关如何创建对象的任何建议吗?
EDIT - Thanks to the insightful comments, it seems maybe creating an object is a better way to go. Any suggestions on how to create an object instead?
答
您可以使用 .each()
迭代元素并将名称和值添加到地图中(平原对象)像这样:
You can use .each()
to iterate over the elements and add the names and values to a map (a plain object) like this:
var map = {};
$(".activeInput").each(function() {
map[$(this).attr("name")] = $(this).val();
});
alert(map.key1); // "red"
查看行动 。
See it in action.