【发布时间】:2013-05-05 10:47:42
【问题描述】:
要监听元素上的事件,我认为是在文档级别监听:
$(document).on('click', '.myclass', function() {/*do something*/});
比在元素级别上监听的样式更好:
$('.myclass').on('click', function() { /*do something*/ });
原因是第一种样式也可以应用于动态添加的新元素。你还可以看到这种风格在 Bootstrap 中被大量使用:https://github.com/twitter/bootstrap/blob/master/js/bootstrap-alert.js
我想广泛使用第一种样式。但我想知道这种风格是否有任何缺点,比如性能?
【问题讨论】:
-
第二个也适用于动态添加的元素,但仅适用于
.myclass元素中的元素。 -
@roasted: no, seems to work for dynamically-added elements too,只要它们在
.myclass元素内。 -
您可能想阅读stackoverflow.com/a/1688293/218196,尽管这主要列出了好处。
-
@DavidThomas 你是对的,我误解了你的说法
-
@DavidThomas,如果一个新的
.myclass添加到 DOM 中,似乎不能被解雇。我之前是指这种问题,所以我想切换。
标签: jquery jquery-events