【发布时间】:2015-08-15 21:30:08
【问题描述】:
我正在尝试创建一个 JavaScript 函数,该函数使用字符串作为结构创建对象并从 DOM 数据中填充它。
例如,以下字符串可能如下所示:
some.example.here = "hello"
some.example.there = "hi"
other.example = "heyo"
应该创建这个对象:
{
some: {
example: {
here: "hello",
there: "hi"
},
other: {
example: "heyo
}
}
上述数据来自 DOM,并在标记为“将数据读入对象”的代码段中加载。数据加载正常,对象结构也设置正常,但数据没有放入数据字段。
这是函数的代码:
function getDataFromElement(element) {
obj = {};
$(element)
.find("[data-value]")
.each(function() {
// create object node
valueObj = {};
currentValueObj = valueObj;
$.each($(this).attr("data-value").split("."), function(i, objpath) {
currentValueObj[objpath] = {};
currentValueObj = currentValueObj[objpath];
});
// read data into object
if($(this).is("[data-putvalue]") && $(this).attr("data-putvalue") != "html") {
currentValueObj = $(this).attr($(this).attr("data-putvalue"));
} else {
currentValueObj = $(this).html();
}
console.log(currentValueObj);
// combine with previous gathered data
obj = $.extend(true, {}, obj, valueObj);
});
return obj;
}
有人知道该怎么做吗?
【问题讨论】:
-
可以在问题中包含
html吗? , 创建 stacksn-ps , jsfiddle jsfiddle.net 演示? -
currentValueObj = currentValueObj[objpath];的目的是什么? -
在第二个 each 循环中,我试图创建对象结构,因此循环遍历字符串的每个元素,创建一个具有当前字符串元素名称的新子元素
currentValueObj[objpath] = {};并使用currentValueObj = currentValueObj[objpath];进入该子元素,以便在下一个循环遍历中创建下一个子元素。 -
currentValueObj在每次迭代时都会被覆盖?可以在 Question 中包含html,创建stacksn-ps来演示吗?
标签: javascript object dom