我有一个创建按钮的工厂,
var btnFactory = (fn, text) => {
var btn = $(`<button>${text}</button>`);
btn.bind("click", fn);
return btn;
};
我希望能够将多个按钮、已绑定(bind)到处理程序的事件插入到一个元素中,这样我最终会得到,
<div>
<button>Button1</button>
<button>Button2</button>
</div>
我正在尝试使用 .html()
来实现它,但到目前为止我还没有想到。
最佳答案
你不需要 jQuery(而且它更高效)
// reusable template element for cloning
const btnTemplate = (() => {
const bt = document.createElement("button")
bt.type = "button"
// other things you want all buttons to have, classname, etc.
return bt
})()
const btnFactory = { fn, text } => {
const btn = btnTemplate.cloneNode(false)
btn.onclick = fn
btn.innerHTML = text
return btn
}
可以像这样使用
const items = [
{ text: "Button1", fn: e => console.log("Button1 clicked") },
{ text: "Button2", fn: e => console.log("Button2 clicked") }
]
// Higher-order helper to fold a collection and a factory into
// a documentFragment
const intoDocFrag = (factoryFn, xs) =>
xs.reduce((frag, x) => {
frag.appendChild(factoryFn(x))
return frag
}, document.createDocumentFragment())
document.body.appendChild(intoDocFrag(btnFactory, items))
关于javascript - 如何插入具有绑定(bind)事件的多个按钮?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49280664/