我正在用javascript创建一个名称空间,以循环遍历表单并创建一个对象。调用时,函数的目标是循环遍历所有特定的表单类型,并构造一个对象,该对象具有一个键,该键是html输入的名称,值是其当前值。然而,它不断返回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;
}
您想要从.each()
调用中获得var current_object = {};
声明。.each()
函数的每一次迭代都会重新声明它,并有效地擦除它。同时忘记$.extend()
。
var data = {};
container.find('input[type="radio"]:checked').each(function() {
data[this.name] = this.value;
});
return data;
不过,从您当前代码的快速浏览中未经测试。
您需要指定键和索引值,类似于thtat:
array.each(function(index, value) {
alert(index + ': ' + value);
});
在您的情况下:
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(index,value) {
var current_object = {}; //loop temporary object
var current = value; //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;
}
通过查看全局范围来解决问题。上面的代码似乎起了作用,但我的全局命名空间混淆了每个循环中的current = $(this)
和this.data,后者是表单数据的全局对象。
这是我的表单提交名称空间:
this.data = {};
this.property_status = function() {
var property_status = {};
this.container.children('form').each(function() {
var current = $(this);
property_status[current.attr('data-property_id')] = get_form_data.radio(current);
});
$.extend(this.data, property_status);
};
以及get_form_data名称空间:
get_form_data.radio = function(container) {//will return the value
var form_data = {};//function data object to return
container.find('input[type="radio"]:checked').each(function() {
form_data[this.name] = this.value;
});
return form_data;
}
有什么优化建议吗?