我创建了一个函数,可以将任何类型的 JSON 数据遍历到 UL/LI 中。现在我需要做相反的事情,将 UL/LI 转换回 JSON 对象。如果可能的话,我想在 JQuery 中执行此操作。那么我该如何将嵌套 UL/LI 转回其原始 JSON 对象呢?
var traverseJson = function(jsonObj) {
"use strict";
var htmlOut = "",
value,
inputv,
prop;
for (prop in jsonObj) {
if (jsonObj.hasOwnProperty(prop)) {
value = jsonObj[prop];
switch (typeof value){
case "object":
htmlOut += "<li><b>" + prop + "</b><span>" + traverseJson(value) + "</span></li>";
break;
default:
inputv = "<span>" + value + "</span>";
htmlOut += "<li class='val'><b>" + prop + ":</b>" + inputv + "</li>";
break;
}
}
}
return "<ul>" + htmlOut + "</ul>";
};
最佳答案
那么你要做的就是迭代 li 元素。
function parseList() {
var outObj = {};
$("li").each(function () {
var propName = $(this).children("b").html();
var propValue = $(this).children("span").html();
outObj[propName] = propValue;
});
return outObj;
}
关于javascript - 将 HTML 遍历到 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16552906/