JavaScript练习 - convertHTMLToJson
发布时间:2022-09-19 15:46:36 211 相关标签: # vue.js# html# edge
在使用vue时,我们常说到的一个概念就是虚拟DOM。那么虚拟DOM是什么?虚拟DOM就是根据真实DOM模拟出的一个JSON对象。在操作DOM时,不是直接去操作DOM,而是先修改虚拟DOM,然后再选择性的更新真实DOM。
为什么这么做?操作真实DOM要比操作虚拟DOM慢?
在写原生JS的时候,我们要可能的避免频繁的直接操作DOM。因为操作DOM可能会经过浏览器的重排重绘,消耗性能,现在JS中处理会提效很多。所以虚拟DOM的出现,为此提供了便利。
那么虚拟DOM是怎么来的呢?这里做一个简单的实现:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<div class="container" id="container">
<article class="article" id="article">
<header class="header">头部</header>
<section class="section">章节1</section>
<section class="section">章节2</section>
<section class="section">章节3</section>
<footer class="footer"><div>备案</div><div>链接</div></footer>
</article>
</div>
<script>
function convertHtmlToJson(node) {
let result = {};
result.classNames = node.className;
result.id = node.id;
result.nodeValue = node.firstChild.nodeValue;
result.tagName = node.tagName;
result.children = [];
if (node.children.length > 0) {
for ( let child of node.children) {
child.localName.toLowerCase() !== 'script' &&
result.children.push(convertHtmlToJson(child));
}
}
return result;
}
const result = convertHtmlToJson(document.body);
console.log(result);
</script>
</body>
</html>

文章来源: https://blog.51cto.com/u_11071029/5641245
特别声明:以上内容(图片及文字)均为互联网收集或者用户上传发布,本站仅提供信息存储服务!如有侵权或有涉及法律问题请联系我们。
举报