fudx / learnNotes

刷题笔记哦
0 stars 0 forks source link

13、json转dom #13

Open fudx opened 1 year ago

fudx commented 1 year ago
<body>
  <div id="app"></div>
</body>

const json = {
    tag: 'div',
    attrs: {
        id: 'root',
    },
    children:[
        {
            tag: 'p',
            attrs:{
                class: 'red'
            },
            children: ['浮动许']
        },
        {
            tag: 'ul',
            children: [
                {
                    tag: 'li',
                    children:[ '2']
                },
                {
                    tag: 'li',
                    children:[ '2']
                }
            ]
        }
    ]
}

function jsonToDom(json){
     // ... todo
}
const dom = jsonToDom(json)
app.appendChild(dom)

在html显示为

<div id="app">
  <div id="root">
    <p class="red">浮动许</p>
     <ul>
       <li>2</li>
       <li>2</li>
     </ul>
   </div>
</div>
fudx commented 1 year ago
function jsonToDom(json){
     // ... todo
     if(typeof json === 'string') {
        return document.createTextNode(json)
     }
     const _dom = document.createElement(json.tag)
     if(json.attrs) {
        for(let [key,value] of Object.entries(json.attrs)) {
            _dom.setAttribute(key,value)
        }
     }

     if(json.children && json.children.length) {
        json.children.forEach(domJson => {
            _dom.appendChild(jsonToDom(domJson))
        });
     }
     return _dom
}
const dom = jsonToDom(json)
app.appendChild(dom)
fudx commented 3 months ago

示例 JSON 输出 假设 HTML 如下:

<div id="container" class="my-container">
  <h1>Hello, World!</h1>
  <p>This is a paragraph.</p>
  <ul>
    <li>Item 1</li>
    <li>Item 2</li>
  </ul>
</div>

上面的代码会输出如下 JSON:

{
  "tag": "div",
  "attributes": {
    "id": "container",
    "class": "my-container"
  },
  "children": [
    {
      "tag": "h1",
      "text": "Hello, World!"
    },
    {
      "tag": "p",
      "text": "This is a paragraph."
    },
    {
      "tag": "ul",
      "children": [
        {
          "tag": "li",
          "text": "Item 1"
        },
        {
          "tag": "li",
          "text": "Item 2"
        }
      ]
    }
  ]
}
fudx commented 3 months ago
function domToJson(element) {
  const obj = {
    tag: element.tagName.toLowerCase()
  };

  // 获取元素的属性
  const attributes = element.attributes;
  if (attributes.length > 0) {
    obj.attributes = {};
    for (let i = 0; i < attributes.length; i++) {
      const attr = attributes[i];
      obj.attributes[attr.name] = attr.value;
    }
  }

  // 获取元素的文本内容
  if (element.childNodes.length === 1 && element.childNodes[0].nodeType === Node.TEXT_NODE) {
    obj.text = element.childNodes[0].textContent.trim();
  } else {
    // 递归处理子元素
    const children = element.children;
    if (children.length > 0) {
      obj.children = [];
      for (let i = 0; i < children.length; i++) {
        obj.children.push(domToJson(children[i]));
      }
    }
  }

  return obj;
}

// 示例:选择一个 DOM 元素
const element = document.getElementById('container');

// 将 DOM 转换为 JSON
const json = domToJson(element);
console.log(JSON.stringify(json, null, 2));