javascript - 如何插入具有绑定(bind)事件的多个按钮?

标签 javascript jquery

我有一个创建按钮的工厂,

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/

相关文章:

javascript - 构建高阶组件并将其应用于 redux connect

javascript - jQuery "$(...).effect is not a function"

javascript - 获取表中的所有div到数组

javascript - 如何将 "Ken Burns Effect"添加到 Swiper?

javascript - jQuery 不会 append 在文档就绪时声明的克隆

javascript - Youtube 嵌入视频的观看次数不计算在内

javascript - 这个 JQuery 代码是什么意思,什么时候调用它?

javascript - jQuery 的 .delay 方法是如何工作的?

javascript - 为什么 iframe 不能设置其父级的 location.hash?

javascript - 在 handlebars.js 中使用具有数字属性的对象