自动为 element 添加所有事件
This commit is contained in:
parent
52ec69488c
commit
5a39a2eb3d
@ -1,21 +1,16 @@
|
||||
export function createElement({ innerText, textContent, onclick, onchange, ondrop, ondragover, ondragleave, onkeydown, onmouseenter, onmouseleave, readOnly, children = [], dataset, style, classList = [], ...attributes }, tagName = 'div') {
|
||||
export function createElement({ innerText, textContent, readOnly, children = [], dataset, style, classList = [], ...attributes }, tagName = 'div') {
|
||||
const element = document.createElement(tagName)
|
||||
for (const key in attributes) element.setAttribute(key, attributes[key])
|
||||
for (const key in attributes) {
|
||||
if (key.startsWith('on')) element[key] = attributes[key] // 如果是事件则直接赋值
|
||||
else element.setAttribute(key, attributes[key]) // 否则是属性则使用setAttribute
|
||||
}
|
||||
if (style) Object.assign(element.style, style)
|
||||
if (classList.length) element.classList.add(...classList)
|
||||
if (textContent) element.textContent = textContent
|
||||
if (innerText) element.innerText = innerText
|
||||
if (readOnly) element.readOnly = readOnly
|
||||
if (onkeydown) element.onkeydown = onkeydown
|
||||
if (onchange) element.onchange = onchange
|
||||
if (onclick) element.onclick = onclick
|
||||
if (dataset) Object.assign(element.dataset, dataset)
|
||||
if (children) children.forEach(child => element.appendChild(child))
|
||||
if (onmouseenter) element.onmouseenter = onmouseenter
|
||||
if (onmouseleave) element.onmouseleave = onmouseleave
|
||||
if (ondrop) element.ondrop = ondrop
|
||||
if (ondragover) element.ondragover = ondragover
|
||||
if (ondragleave) element.ondragleave = ondragleave
|
||||
return element
|
||||
}
|
||||
|
||||
|
Loading…
Reference in New Issue
Block a user