假设我想使用 DOM 创建一个输入元素。而不是做这样的事情
var input = document.createElement("input");
input.setAttribute("class", "my-class");
input.setAttribute("type", "checkbox");
input.setAttribute("checked", "checked");
有没有一种更干燥的方法将这三行代码写成一行。
我知道你可以做这样的事情
var attributes = ["class", "type", "checked"];
var values = ["my-class", "checkbox", "checked"];
for (var i = 0; i < attributes.length; i++) {
input.setAttribute(attributes[i], values[i])
end
问题是,只有当您需要添加大量属性时,这才有用。如果你只有两三个,那就更不干燥了。
我可以把这段代码写干吗?
最佳答案
我个人认为你正在采取DRY太远了(这三个语句做了不同的事情,所以我不明白它为什么不干燥。)但是如果你必须抽象它,只需编写一个函数来完成它:
var input = document.createElement("input");
function setAttributes(el, options) {
Object.keys(options).forEach(function(attr) {
el.setAttribute(attr, options[attr]);
})
}
setAttributes(input, {"class": "my-class", "type": "checkbox", "checked": "checked"});
console.log(input);
关于javascript - 可以使用 DOM 的 setAttribute 函数设置多个属性吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30535595/