使用jquery.each()循环创建对象键 [英] Creating Object Key with jquery.each() loop
问题描述
我正在javascript中创建一个名称空间来遍历表单并创建一个对象。调用函数的目的是遍历所有特定的表单类型,并构造一个具有键的对象,该键是html输入的名称,值是其当前值。但是,它一直返回undefined。
I'm creating a namespace in javascript to loop through a form and create an object. The goal of the function when called is to loop through all of a certain form type and construct an object that has a key which is the html input's name and the value as its current value. However, it keeps returning undefined.
任何帮助将不胜感激:
get_form_data.radio = function(container) { //will return the value
var data = {}; //function data object to return
container.find('input[type="radio"]:checked').each(function() {
var current_object = {}; //loop temporary object
var current = $(this); //current element
var current_key = current.attr('name'); //property category
var current_value = current.attr('value'); //value to update the database with
current_object[current_key] = current_value; //temporary object
console.log(current_object.length); //RETURNS UNDEFINED
$.extend(data, current_object);
});
console.log(data.length); //returns undefined
return data;
}
推荐答案
你想得到的 var current_object = {};
声明超出 .each()
调用。 .each()
函数的每次迭代都会重新声明它,并有效地删除它。并忘记 $。extend()
。
You want to get the var current_object = {};
declaration out of the .each()
call. Each iteration of the .each()
function redeclares it, and effectively erases it. And forget about $.extend()
as well.
var data = {};
container.find('input[type="radio"]:checked').each(function() {
data[this.name] = this.value;
});
return data;
通过快速浏览当前代码未经测试。
Untested though from a quick skim of your current code.
这篇关于使用jquery.each()循环创建对象键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!