2012-04-04 35 views

回答

6

我會想象使用jquery.on()將是理想的。

$("#divWithHugeAmountsOfChildDiv").on("mousedown", 
             ".childCLASSEStoMouseDown", 
             function() 
{ 
    alert("Booya!"); 
}); 

是HTML可能看起來像:

<body> 
    <!-- lots of other elements --> 
    <div id="divWithHugeAmountsOfChildDiv"> 
    <!-- lots of different type of elements --> 
    <div class="childCLASSEStoMouseDown">Booya?</div> 
    <!-- lots of different type of elements --> 
    </div> 
    <!-- lots of other elements --> 
</body> 

根據需要更改jQuery選擇...

的爲什麼jQuery的文檔的On方法很好解釋。

+0

謝謝,我已經使用jQuery.on(),但沒想到與委派事件處理這樣使用它! – Adam 2012-04-04 23:53:30

2

有了這麼多的子div,你應該肯定使用jQuery的.on()委託事件處理。這會爲您提供父級上的一個事件處理程序,而不是子級上的4000個事件處理程序。安裝和初始化也會更快。

如果您使用.on()的委託形式,您將不必親自檢查e.target,因爲jQuery將爲您執行此操作。

以這種方式使用.on()的語法是這樣的:在jQuery doc for .on()

$('parentSelector').on('mousedown', 'child selector', function(e) { 
    // code here 
    // "this" will be the object that initiated the event 
}); 

更多信息。

4

使用jQuery的.on()已經爲你做了。它將事件處理程序綁定到某個父級並檢測子級事件。它擁有超過.live().bind()性能優勢,以及直接綁定事件像.click()等,因爲:

  • 不像.live(),結合事件的document,用,.on(),你負責什麼父綁定。

  • .live()綁定到document這是文檔的根。起泡的事件將進一步發展。與.on(),你可以找到最近的共同父母綁定該事件。泡沫會減少出行 - 性能優勢

  • .on(),你只有一個處理程序綁定到父,不像.bind()和直接事件綁定,結合每個元素的基礎上的事件 - 對於很多元素都不好。

  • .on()更容易記住。

  • 當獲得目標時,在.on()裏面,「this」永遠是目標元素。從不擔心跨瀏覽器甚至是目標。 jQuery爲你做。

所以「這個」這個代碼:

$(element).on('click','someElement',function(){ 
    //the value of "this" in here is the DOM element target of the event 
});