jquery $('body').on('click') 总是需要 .off('click') 以避免触发多个事件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12496436/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
jquery $('body').on('click') always needs .off('click') to avoid multiple event firing
提问by Kinesias
I have a page where I list my crew members (show_crew.php). The page runs on with infinite scrolling plugin, like Google Images does. At first, I show 10 entries. If the user reaches the bottom of show_crew.php, a new 'show_crew.php' is appended to the old one, showing the next 10 entries.
我有一个页面,我列出了我的船员 (show_crew.php)。该页面使用无限滚动插件运行,就像 Google 图片一样。首先,我显示 10 个条目。如果用户到达 show_crew.php 的底部,新的“show_crew.php”会附加到旧的“show_crew.php”,显示接下来的 10 个条目。
I heave some Jquery functions embedded in show_crew.php, where I bind events via
我在 show_crew.php 中嵌入了一些 Jquery 函数,在那里我通过绑定事件
$('body').on('click', 'myButton[rel=<? echo $user['id'] ?>]', function() {
console.log('foo');
})?
Now, as show_crew.php is appended multiple times, the event is also bound to the same button multiple times. I can fix this problem via $('body').off('click', 'myButton')
EACH TIME.
现在,由于多次附加 show_crew.php,事件也多次绑定到同一个按钮。我可以通过$('body').off('click', 'myButton')
EACH TIME解决这个问题。
This looks ugly. Is there a more elegant way?
这看起来很丑。有没有更优雅的方式?
thanks, matt
谢谢,马特
回答by zzzzBov
You only need to bind the delegated events once. Don't rebind every time the content is loaded.
您只需要绑定一次委托事件。每次加载内容时不要重新绑定。
Using the format of $('body').on('click', '...selector...', function () {...})
will delegate the event handler to the <body>
element. What this means is that the body will catch all click
events and check whether they occurred on an element that matches ...selector...
. If it did, it'll trigger the event handler as if it were triggered on the matched element.
使用 的格式$('body').on('click', '...selector...', function () {...})
将事件处理程序委托给<body>
元素。这意味着主体将捕获所有click
事件并检查它们是否发生在匹配的元素上...selector...
。如果是这样,它将触发事件处理程序,就好像它是在匹配的元素上触发的一样。
Once you've added the delegate listener, there's no need to worry about rebinding, as the children of <body>
can change, and the delegate will persist for new elements. This is a very good thing™.
一旦您添加了委托侦听器,就无需担心重新绑定,因为 的子代<body>
可以更改,并且委托将为新元素保留。这是一件非常好的事情™。