创建元素和绑定事件的另一个灵活解决方案(
source
)
// creating a dynamic element (container div)
var $div = $("<div>", {id: 'myid1', class: 'myclass'});
//creating a dynamic button
var $btn = $("<button>", { type: 'button', text: 'Click me', class: 'btn' });
// binding the event
$btn.click(function () { //for mouseover--> $btn.on('mouseover', function () {
console.log('clicked');
});
// append dynamic button to the dynamic container
$div.append($btn);
// add the dynamically created element(s) to a static element
$("#box").append($div);
注:
这将为每个元素创建一个事件处理程序实例
(在循环中使用时可能会影响性能)