这些天我正在做一个 jquery 项目,我发现如果我使用像这样的直接事件
$('.selector').click(function(){
});
将完美运行,但在页面部分回发或动态内容的情况下,我必须使用.on 如下
$('body').on('click','.selector',function(){
});
现在我的问题是关于静态内容以及动态内容的工作,所以为什么我不总是直接使用on而不是静态事件之类的click
。
.on是否有任何性能问题
Is there any performance issue with .on
There is no performance issue with .on
. In fact, your first example is just a shortcut for:
$('.selector').on('click', function(){
The difference as you say is the use of $('body').on
delegates the event for elements that are not yet in the DOM which naturally will require more work from the browser. If you need the delegation on the document or body then use that, otherwise use the other way.