由於您確實只測試單個元素是否與選擇器匹配,因此使用事件委派從左到右和從右到左是沒有好處的。例如,下面的將相當於代碼在你的問題:
$(document).on("click",function(e){
if ($(e.target).is("#context a")) {
// do something
}
})
選擇工作左至右VS從右到左不會有任何這裏的性能優勢。當然,你仍然可以做,如果你想:
$(document).on("click",function(e){
if ($("#context").find("a").filter(function(){
return this == e.target;
}).length) {
// do something
}
})
然後,你必須考慮到這是在新的瀏覽器優化使用Element.matches()
$(document).on("click",function(e){
if (e.target.matches("#context a")) {
// do something
}
})
// note, Element.matches is only supported in chrome 34, all
// other browsers require a vendor prefix at this time
// (which jquery takes care of)
爲什麼不'$(」 #context ')。在(' 點擊」, 'A',函數(){})'? – Johan
#上下文也是動態加載的。 –
在這種情況下,從左到右會有什麼好處?這不像它在這種情況下使用優化的方法。 –