是的,你可以看看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
另外,如果你只想的處理程序,以火的時候,點擊其中一個孩子,你可以通過delegate
或on
使用事件委派:
$('.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
(它看起來每個人都喜歡)之間有所不同。
+1感謝您的詳細信息 – 2013-03-02 11:38:56
我更喜歡委託以上,但 - 「從jQuery 1.7開始,.delegate()已被.on()方法取代。」鏈接:http://api.jquery.com/delegate/ - 所以我想這取決於你的JQuery版本,而不是偏好,或者我錯了嗎?只是好奇。 – 2013-03-02 11:40:17
@Xeano:「取代」並不意味着「棄用」。 '委託'還沒有被棄用,甚至在v1.9.2中都沒有。 – 2013-03-02 11:41:29