我遇到的情况是,我在网站的特定部分的许多实例中使用名为data
的{{1}}属性,而不是绑定大量单独的点击事件,我决定只使用一个并使用如下的开关:
data-command
然而,在尝试通过$('[data-command]').on('click', function(event) {
// Prevent default click action
event.preventDefault();
// Get command
var command = $(event.target).data('command');
switch (command) {
// Do stuff...
}
// Prevent default click action (IE 8)
return false;
});
加载数据时,它只是一个问题。
这显然有效..
AJAX
...但由于它应该在网站的该部分的许多不同页面上工作,因此上述内容不适用于所有页面。
我可能只是确保给父包装器一个特定的$('#existing_element').on('click', '[data-command]', function(event) {
,我加载了所有的ajax数据,但这意味着要用两个单独的绑定事件做两个单独的绑定事件相同的代码。
我也可以这样做来涵盖所有基地..
id
......但是,将元素绑定到文档可能并不是一个明智的想法。
修改:Html数据正在通过jQuery的$(document).on('click', '[data-command]', function(event) {
方法加载到DOM
。
任何 clean 方式我可以处理这个或者我应该创建两个不同的绑定事件来处理每种情况吗?
答案 0 :(得分:2)
Event delegation is the best approach to bind events on dynamically created elements. Since you don't want to use event delegation, use following approach to bind events.
$('[data-command]').off('click').on('click', clickHandler);
// Somewhere in the same scope
function clickHandler(e) {
// Handle click event here
}
Add this after the dynamically created elements are added using html()
.
off('click')
will first unbind the click event handlers that are applied previously and then on('click',
will bind the click handler on all the elements matching selector.
Edit
This seems to be repeating the same code again and again. Can't I keep it DRY?
Yes, you can keep the code DRY and clean by creating a function to bind events and call the same function when you want to bind event.
function clickHandler(e) {
// Handle click event here
}
function bindEvent() {
$('[data-command]').off('click').on('click', clickHandler);
}
$(document).ready(bindEvent);
...
$.ajax({
...
success: bindEvent
....