我正在动态创建一个 div。我想向它添加一个 onClick() 事件。
如何添加 onClick,如 <div class="something" id="btnHome" onClick="return true">
到这个?
abc.append(
$('<div />', { class: 'something', id: 'btnHome' })
);
编辑:
我正在寻找类似这样的答案
$('<div />', { class: 'something', id: 'btnHome' onClick: 'return true' })
最佳答案
使用event delegation
:
Event delegation allows us to attach a single event listener, to a parent element, that will fire for all descendants matching a selector, whether those descendants exist now or are added in the future.
对于动态添加的元素,使用parent为添加的元素添加事件。
$(staticParentSelector).on('click', '.something', function () {
// Event Handler Code here
});
你也可以使用document
,但这会降低性能
$(document).on('click', '.something', function () {
// Event Handler Code here
});
请参阅 jQuery 文档以了解 on
关于javascript - 添加一个 onClick 事件到 append(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29728254/