JavaScript 设置多个属性
const setAttributes = (element, attributes)=>{
for(let key in attributes){
if(Object.prototype.toString.call(attributes[key]) === '[object Object]'){
setAttributes(element[key],attributes[key]);
}else{
element[key] = attributes[key];
}
}
};
let testBtn = document.createElement('button');
// 设置多个属性
setAttributes(testBtn, {textContent: '测试按钮', id: 'testBtn', className: 'test'});
// 支持函数
setAttributes(testBtn, {onclick: ()=>{ alert('Hello World!'); }});
// 支持多层
// 等价于 testBtn.style.cssText = `width: 100%; height: 100%;`;
setAttributes(testBtn, {style: {cssText: `width: 100%; height: 100%;`}});
在没有用 Jquery 的时候,写了这个函数,现在用不着了。