在DOM操作练习中,我正在学习如何使用纯Javascript创建HTML元素。即类似这样的东西:
document.createElement()
setAttribute()
appendChild()
我必须创建一个函数,该函数允许用户将对象作为参数传入以将属性设置到元素上。该对象包含任意数量的键(属性)和值(属性值)。即属性可以是“ src”,值可以是“ image.jpg”。那种效果。调用函数时,用户可以根据需要将任意数量的属性传递给该对象。
同一功能还创建了将应用于属性的元素,但这不是我所坚持的部分。
如何设置函数以接受对象并通过setAttribute()方法打开该对象的内容?
附带说明,对于代码和JS来说是非常新的,请忍受我:P
答案 0 :(得分:1)
let attributes = {
"class": "some-class",
"id": "unique-id",
"style": "border: 1px solid tomato"
}
let title = document.createElement("h1");
title.textContent = "Title!";
Object.keys(attributes).forEach( key => {
title.setAttribute( key, attributes[key] );
// key is elem
// value is attributes[key]
});
document.body.appendChild( title );
希望这会有所帮助。