2013-03-02 65 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。