如何将 HTML <div..../div> 转换为具有 name:value 属性的

我有一个包含多个 HTML div 的文本文件,例如


<div id="ID_a" name="VEC" class="cat" title ="scene,-12, 0.5, 0, 1" text = "$\omega =9$">   </div>  

<div id="ID_b" name="VEC" class="cat" title ="scene,-12, 0.5, 0, 3" text = "$\alfa = 2$">   </div>  

<div id="ID_c" name="VEC" class="cat" title ="scene,-12, 0.5, 0, 4" text = "$\beta = 30.5$"></div>  

<div id="ID_d" name="VEC" class="cat" title ="scene,-12, 0.5, 0, 2" text = "$\gamma = 90$"> </div>  

我希望将<div ...> </div>文本中的每个语句(使用 javascript)转换为 javascript 对象规范语句,例如


Coll[1] = {id:"ID_a", name: "VEC", class: "cat", title:"scene,-12, 0.5, 0, 1", text = "$\omega =9$" }; 

Coll[2] = {id:"ID_a", name: "VEC", class: "cat", title:"scene,-12, 0.5, 0, 3", text = "$\alfa = 2$" }; 

Coll[3] = {id:"ID_a", name: "VEC", class: "cat", title:"scene,-12, 0.5, 0, 4", text = "$\beta = 30.5$" }; 

Coll[4] = {id:"ID_a", name: "VEC", class: "cat", title:"scene,-12, 0.5, 0, 2", text = "$\gamma = 90$" }; 

我想知道是否有一种简单的方法可以做到这一点?


编辑:我想在不使用 DOM 模型或将 div 作为 html 文件的一部分加载的情况下使用纯 javascript 来完成。抱歉之前没有说清楚。


翻翻过去那场雪
浏览 149回答 2
2回答

波斯汪

这是你想要的?let divs = document.querySelectorAll('div');let obj = [];divs.forEach(element => {&nbsp; let e = {&nbsp; &nbsp; id: element.id,&nbsp; &nbsp; name: element.getAttribute("name"),&nbsp; &nbsp; class: element.className,&nbsp; &nbsp; title: element.title,&nbsp; &nbsp; text: element.getAttribute("text")&nbsp; };&nbsp; obj.push(e);})console.log(obj)<div id="ID_a" name="VEC" class="cat" title="scene,-12, 0.5, 0, 1" text="$\omega =9$"> </div><div id="ID_b" name="VEC" class="cat" title="scene,-12, 0.5, 0, 3" text="$\alfa = 2$"> </div><div id="ID_c" name="VEC" class="cat" title="scene,-12, 0.5, 0, 4" text="$\beta = 30.5$"></div><div id="ID_d" name="VEC" class="cat" title="scene,-12, 0.5, 0, 2" text="$\gamma = 90$"> </div>

红糖糍粑

假设您将所有 div 作为字符串加载,您可以将每个字符串映射到一个对象。这可以通过按每个属性拆分字符串(通过regex)然后通过reduce将这些字符串转换为对象来完成。因为某些值包含等号,所以我搜索第一次出现的索引,并在将其作为对象返回之前将字符串拆分为带有切片的键和值。const divs = [  '<div id="ID_a" name="VEC" class="cat" title ="scene,-12, 0.5, 0, 1" text = "$\omega =9$">   </div>',  '<div id="ID_b" name="VEC" class="cat" title ="scene,-12, 0.5, 0, 3" text = "$\alfa = 2$">   </div>',  '<div id="ID_c" name="VEC" class="cat" title ="scene,-12, 0.5, 0, 4" text = "$\beta = 30.5$"></div>',  '<div id="ID_d" name="VEC" class="cat" title ="scene,-12, 0.5, 0, 2" text = "$\gamma = 90$"> </div>',];const Coll = divs.map((div) => {  const parts = div.match(/[\w-]+\s?=\s?"[^"]*"/g);  const objectified = parts.reduce((obj, str) => {    const index = str.indexOf("=");    const key = str.slice(0, index);    const value = str.slice(index + 1, str.length);    obj[key] = value;    return obj;  }, {});    return objectified;});console.log("Single value:", Coll[0].id);console.log(Coll);.as-console-wrapper { max-height: 100% !important; }
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript