欢迎访问 如意编程网!

如意编程网

当前位置: 首页 > 前端技术 > HTML >内容正文

HTML

HTML(DOM)与JavaScript嵌套数组之间相互转换

发布时间:2022/11/16 HTML 10 老码农
如意编程网 收集整理的这篇文章主要介绍了 HTML(DOM)与JavaScript嵌套数组之间相互转换 小编觉得挺不错的,现在分享给大家,帮大家做个参考.

1. [代码][JavaScript]代码     
/*
<html>
<head>
  <title>HTML RESTructure</title>
<style>
</style>
<script>
*/
// workDOM函数遍历目标元素或节点
// 有两种模式:
//   1. `element`模式(默认)(包含所定义的元素项)
//   2. `node`模式(包含文本节点在内的所有节点)
function walkDOM(mode) {
  var m = mode || "element";
  var f = "firstElementChild",
      n = "nextElementSibling";
  if (m === "node") {
    f = "firstChild";
    n = "nextSibling";
  }


  return function _(val, func) {
    func(val);
    val = val[f];
    while (val) {
      _(val, func);
      val = val[n];
    }
  };
}
// html2ja函数将HTML目标元素转换为JavaScript数组,
// 这个函数中调用了eval函数, 并且为每一个目标范围
// 内的元素加了一个index属性(这是特意设置的)。
function html2ja(elt) {
  var walk = walkDOM(),
      lis;
  walk(elt, function (el) {
    var pe = el.parentElement,
        pes = el.previousElementSibling;


    var sel = el.tagName;
    if (el.className)
      sel += ' .' + el.className;
    if (el.id)
      sel += ' #' + el.id;


    if (el === elt) {
      el.index = '0';
      lis = [sel];
    } else {
      if (pes) {
        el.rank = pes.rank + 1;
      } else {
        el.rank = 1;
        }
      var t = pe.index.split(',').slice(0,-1).concat(el.rank);
      el.index = t.concat(0).join(',');
      eval('lis[' + t.join('][') + '] = [sel];');
    }
  });
  return lis;
}


window.onload = function () {
  var ind = '';
  var showJa = function _(o) {
    var i,
        s = '';   
    for (i = 0; i < o.length; i++) {
      var s1;
      if (typeof o[i] === 'object') {
        ind += '\t';
        s = s.slice(0, -1) + ',\n' + ind + _(o[i]) + ']';
      } else {
        s = s.slice(0, -1) + '["' + o[i] + '"]';
        }​
     }
    ind = ind.slice(0, -1);
    return s;
  };


  document.getElementById("code-pre").innerText = showJa(html2ja(document.documentElement));
};http://www.huiyi8.com/yuanma/​
/*
</script>
</head>
<body>
<div , tahoma, verdana, helvetica; color: rgba(0, 0, 0, 1); text-transform: none; text-indent: 0; letter-spacing: normal; word-spacing: 0; float: none; display: inline !important; white-space: normal; orphans: 2; widows: 2; font-size-adjust: none; -webkit-text-size-adjust: auto; -webkit-text-stroke-width: 0px'>*/

总结

以上是如意编程网为你收集整理的HTML(DOM)与JavaScript嵌套数组之间相互转换的全部内容,希望文章能够帮你解决所遇到的问题。

如果觉得如意编程网网站内容还不错,欢迎将如意编程网推荐给好友。