2 回答

TA貢獻(xiàn)1811條經(jīng)驗(yàn) 獲得超4個(gè)贊
這是你想要的?
let divs = document.querySelectorAll('div');
let obj = [];
divs.forEach(element => {
let e = {
id: element.id,
name: element.getAttribute("name"),
class: element.className,
title: element.title,
text: element.getAttribute("text")
};
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>

TA貢獻(xiàn)1815條經(jīng)驗(yàn) 獲得超6個(gè)贊
假設(shè)您將所有 div 作為字符串加載,您可以將每個(gè)字符串映射到一個(gè)對(duì)象。這可以通過(guò)按每個(gè)屬性拆分字符串(通過(guò)regex)然后通過(guò)reduce將這些字符串轉(zhuǎn)換為對(duì)象來(lái)完成。
因?yàn)槟承┲蛋忍?hào),所以我搜索第一次出現(xiàn)的索引,并在將其作為對(duì)象返回之前將字符串拆分為帶有切片的鍵和值。
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; }
添加回答
舉報(bào)