2014-02-20 13 views
1

JQuery從右向左查找選擇器匹配的元素。通常,如果我想從左至右選擇,我可以這樣做:$('#context').find('a')JQuery's on():如何讓JQuery從左到右找到選擇器?

我使用on()來爲動態生成的元素調用事件處理程序,如下所示:$(document).on('click','#context a',function(){})。動態加載#context。在這種情況下,我如何從左至右選擇?

+1

爲什麼不'$(」 #context ')。在(' 點擊」, 'A',函數(){})'? – Johan

+0

#上下文也是動態加載的。 –

+1

在這種情況下,從左到右會有什麼好處?這不像它在這種情況下使用優化的方法。 –

回答

0

由於您確實只測試單個元素是否與選擇器匹配,因此使用事件委派從左到右和從右到左是沒有好處的。例如,下面的將相當於代碼在你的問題:

$(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) 
相關問題