Should I attach my .on('click') event to the document or element

Gig*_*m02 8 javascript jquery javascript-events

Yesterday I was reading the jQuery docs for .on() where was stated:

Avoid excessive use of document or document.body for delegated events on large documents

But today, I was looking at this JSPERF and I notice a better perfomance when the click event is attached to the document.

So right now, i'm confused. The perfomance tests speak against the docs?

Chr*_*ald 7

您的JSPerf在这里测试附加事件的速度,而不是它们对累积页面性能的影响.这是测试的错误!

Javascript事件一直向上传播到文档根目录.这意味着,如果你有一个on("click", ...)关于处理document,然后每一次点击的每一个元素的文件最终会运行事件处理程序中,这样的jQuery可以测试它的起源委托目标相匹配,看它是否应该传递给该事件处理程序.

想象一下,您的页面在文档上有10个不同的委派事件处理程序,所有处理各种点击.每次单击页面中的任何元素时,事件将冒泡到文档根目录,并且必须测试所有10个处理程序以确定应该运行哪个(如果有).

通常,您希望委派事件尽可能在树中尽可能地启用您的功能,因为这会限制可能调用此事件的元素数量,并且您可以提前处理事件以防止它传播到DOM树.