Jquery 事件分配vs.live()

Jquery 事件分配vs.live(),jquery,event-handling,live,Jquery,Event Handling,Live,很久以前,我曾使用此解决方案: $('<div class="ok" />') .appendTo('body'); $('div.ok') .live('click',function(){ alert(); }) $(“”) .附于(“主体”); $('div.ok') .live('click',function(){alert();}) 现在我用这个: $('<div class="ok" />') .appendTo('body') .click(func

很久以前,我曾使用此解决方案:

$('<div class="ok" />')
.appendTo('body');

$('div.ok')
.live('click',function(){ alert(); })
$(“”)
.附于(“主体”);
$('div.ok')
.live('click',function(){alert();})
现在我用这个:

$('<div class="ok" />')
.appendTo('body')
.click(function(){ alert(); })
$(“”)
.appendTo('正文')
。单击(函数(){alert();})
性能差异如何?我认为第二种解决方案更好,因为它不需要live()。
是否总是这样(也有很多元素)?为什么?

第二种方法提供的性能提升可以忽略不计(假设没有大量
div.ok
元素落入DOM),因为DOM不需要再次搜索。另一种选择是使用
html/props
签名:

$("<div>", { 
    'class': "ok",
    'click': function () {
        alert("You clicked the new element!");
    } 
}).appendTo("body");
其工作方式是利用事件的冒泡行为。当您单击一个元素时,单击将遍历DOM,直到它最终到达
文档
对象。jQuery然后检查发起单击的元素是否与选择器匹配(
.ok
),如果匹配,则运行匿名函数

为了获得更好的性能,不要绑定到
文档
,而是绑定到更接近动态添加元素的内容。例如,如果要动态添加
li
元素,请绑定到它们的父元素
ol
ul
。这样,事件在处理之前不需要传播很远

事件委派到位后,您可以从动态添加的
div
本身中删除
单击逻辑:

$("<div>", {'class': 'ok'}).appendTo("body");
$(“”,{'class':'ok'});
性能差异如何

嗯,当你过去使用
live
live
始终绑定到
文档
,并且防止事件冒泡也是不可能的,因为事件是在一路冒泡之后触发的

从这个意义上讲,
live()
对性能不是很友好

您的第二个代码示例在创建对象时直接绑定到对象,与
live()
相比,它的性能更好、更灵活。您现在可以防止事件冒泡等

将创建时的事件绑定到元素直接与使用()上的
相比,指定要绑定到的最接近的静态元素只具有很小的性能优势

// Performs slightly better than on() but cannot be executed from anywhere unless the element is added at the same time.
$('<div class="ok" />').appendTo('body').click(function(){ alert(); })

on()
有一个很大的好处,那就是您可以将元素的添加与事件的绑定分开。

您还知道
.live()
不受欢迎,对吧?是的,我知道。我们可以假设使用.on()@user1392191:如果提供的任何响应已回答您的问题,请将其中一个标记为接受。但是,如果您对此问题仍有疑问,请告知我们。
// Performs slightly better than on() but cannot be executed from anywhere unless the element is added at the same time.
$('<div class="ok" />').appendTo('body').click(function(){ alert(); })
// Can be called in a common init method for example and still work.
$(body).on('click', '.ok', function(){ alert();})