2013-03-02 90 views
3

如果我寫了下面的聽衆,是否有可能檢查哪個「孩子」 DIV被點擊

$('.parent').bind('click', function() { 
//... 
}) 

<div class="parent"> 
    <div class="children1"></div> 
    <div class="children2"></div> 
    <div class="children3"></div> 
</div> 

比如我點擊children2,是否有可能檢查parent下這「孩子」 DIV被點擊?

感謝

回答

8

是的,你可以看看e.target(改變你的處理程序,以接受e作爲參數),可能使用closest拿到第一div祖先實際元素的點擊(如果那些孩子div■找後人)。

$('.parent').bind('click', function(e) { 
    // Here, `e.target` is the DOM element where the click occurred 
    var div = $(e.target).closest('div'); 
}); 

Live Example | Source

另外,如果你只的處理程序,以火的時候,點擊其中一個孩子,你可以通過delegateon使用事件委派:

$('.parent').delegate('div', 'click', function(e) { 
    // Here, `this` is the child div that was clicked 
}); 

// or 

$('.parent').on('click', 'div', function(e) { 
    // Here, `this` is the child div that was clicked 
}); 

Live Example | Source

請注意,參數的順序在delegate(我更喜歡爲了清晰起見)和on(它看起來每個人都喜歡)之間有所不同。

+0

+1感謝您的詳細信息 – 2013-03-02 11:38:56

+0

我更喜歡委託以上,但 - 「從jQuery 1.7開始,.delegate()已被.on()方法取代。」鏈接:http://api.jquery.com/delegate/ - 所以我想這取決於你的JQuery版本,而不是偏好,或者我錯了嗎?只是好奇。 – 2013-03-02 11:40:17

+0

@Xeano:「取代」並不意味着「棄用」。 '委託'還沒有被棄用,甚至在v1.9.2中都沒有。 – 2013-03-02 11:41:29

3

Working Demo

你可以看一下事件的目標。這裏的事件是e。

$('.parent').bind('click', function(e) { 
    console.log(e.target); 
}); 
+0

+1感謝您的演示 – 2013-03-02 11:40:19

0

e.target.className將獲得在哪個事件觸發的div類名。

$('.parent').bind('click', function(e) { 
    if(e.target.className.indexOf('children') != -1) { // <-- Perform function only if any child is clicked 
    // do something 
    } 
}) 
0

您應該使用

$('.parent').on('click', 'div', function() { 
// ... 
}); 

。對(),而應使用.bind的()。 this引用事件處理程序中的點擊div。