javascript - 将 HTML 遍历到 JSON

标签 javascript jquery json

我创建了一个函数,可以将任何类型的 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/

相关文章:

jquery - 使用单独的 .js 文件来处理 Jquery

javascript - Angularjs + 停止将数据更新到变量中

javascript - 设置 location.hash 时防止默认行为

javascript - 在交叉点类型上调用 .map()

Javascript 常见问题解答下拉列表

javascript - 未捕获( promise )错误 : Container is not defined

javascript - 有没有一种方法可以在 springmvc 中的 ajax post 调用之后将我的页面(jsp)重定向到另一个页面(jsp)

javascript - 如何使用 jQuery ajax 在不同主机上检索和显示 html/asp/aspx 页面?

sql - 传递一个对象(.net 或 json 对象)作为 postgresql 函数的输入参数

json - 将 JSON 数据对象从 jquery ajax 传递到 asp.net webmethod