【发布时间】:2017-02-03 08:41:51
【问题描述】:
我创建了一个简单的 javascript 插件,它允许我从特定的 html 元素中收集数据。一个页面可以有 x 个元素(通常最多 20 个),每个元素都有自己的设置。我的问题是返回的对象不是有效的 JSON 格式,因为我收到错误“多个 JSON 根元素”。
我认为原因是因为我在插件中使用的每个函数,它为每个对象创建一个新对象,我试图解决这个问题;结果不好。
所有帮助将不胜感激,在此先感谢!
示例插件
(function($) {
$.fn.collect_data = function() {
this.each(function() {
var id = "#" + ($(this).attr("id"));
// Get numerical value of id
var get_package_id = function() {
var package_id = id.replace(/[^0-9]/g, '');
return package_id;
}
// Packages is the top level container
var get_packages = function() {
var packages = {};
packages = ({[get_package_id()]: {}});
return packages;
}
// Demo information for each invidual package
var get_package_info = function() {
var info = {};
$(id).each(function() {
info = ({
value: 'Some value',
another_value: 'Another value'
});
});
return info;
}
// Demo information for each invidual package
var get_more_info = function() {
var more_info = {};
$(id).each(function() {
more_info = ({
value_more_info: 'Some value',
another_value_more_info: 'Another value'
});
});
return more_info;
}
// Combine the demo information
var result = function() {
var packages = get_packages();
var info = get_package_info();
var more_info = get_more_info();
packages[get_package_id()].info = info;
packages[get_package_id()].more_info = more_info;
return packages;
}
$("#show-data").append(JSON.stringify(result(), null, 2));
});
return this;
}
}(jQuery));
无效结果
{
"33": {
"info": {
"value": "Some value",
"another_value": "Another value"
},
"more_info": {
"value_more_info": "Some value",
"another_value_more_info": "Another value"
}
}
}{
"74": {
"info": {
"value": "Some value",
"another_value": "Another value"
},
"more_info": {
"value_more_info": "Some value",
"another_value_more_info": "Another value"
}
}
}{
"99": {
"info": {
"value": "Some value",
"another_value": "Another value"
},
"more_info": {
"value_more_info": "Some value",
"another_value_more_info": "Another value"
}
}
}{
"124": {
"info": {
"value": "Some value",
"another_value": "Another value"
},
"more_info": {
"value_more_info": "Some value",
"another_value_more_info": "Another value"
}
}
}{
"124": {
"info": {
"value": "Some value",
"another_value": "Another value"
},
"more_info": {
"value_more_info": "Some value",
"another_value_more_info": "Another value"
}
}
}
所有数据可能都应该位于顶级 {} 容器中,而不是每个对象都添加到它们自己的 {} 中。
提前感谢所有帮助
【问题讨论】:
标签: javascript jquery json object