2017-02-14 68 views
0

是否可以从jquery点击事件中排除元素?我的问题的一个简化版本是这样的:用jquery排除元素

CSS

.outerbox{ 
height:100px; 
width:100px; 
background-color:red; 
position:relative; 
} 

.innerbox{ 
height:50px; 
width:50px; 
background-color:yellow; 
margin:auto; 
position: absolute; 
top: 25%; 
left: 25%; 
} 

HTML

<div class="outerbox"> 
    <div class="innerbox"></div> 
</div> 

JQUERY

$(".outerbox").not(".innerbox").click(function() { 
    alert("Red has been clicked, but not the yellow area"); 
}); 

我没有选择不工作,虽然。我试过$(“。outerbox:not('。innerbox')”),结果没有任何效果。任何想法我可以做到这一点?

回答

0

可以使用target属性形成引发事件:

$(".outerbox").on('click', function(event) { 
    var trg = $(event.target); 
    if (trg.hasClass('innerbox')) { 
     // Inner was clicked 
    } 
}) 
4

你不能从具有 click事件停止元素,但你可以捕捉单击事件和传播通过停止DOM。所以,你将有你的外单击事件处理程序正常:

$(".outerbox").click(function() { 
    alert("Red has been clicked, but not the yellow area"); 
}); 

,并添加一个单击处理程序为其做无非就是取消该事件的“内部”的元素:

$(".innerbox").click(function(e) { 
    e.stopPropagation(); 
}); 

Example

+0

谢谢 - 我想我可以与工作! – JohnG

+0

除非你走了,否则点击它会让你觉得使用点击来获得内部框@JohnG –

0

只需更换你的JS代码与此::

$(".outerbox").click(function(event) { 
    if($(event.target).attr('class') == 'outerbox') 
     alert("Red has been clicked, but not the yellow area"); 
}); 
0

除非你重新没有去做任何事情与innerbox点击我会去检查目标。

demo on jsfiddle

$(".outerbox").on('click', function(e) { 
    if (e.target.classList.contains('innerbox')) { 
     return false; 
    } 

    // your code here 
}); 
0

这是所有关于事件冒泡,而不是一个jQuery选择问题。

click事件具有e.eventPhase属性,该属性指示当前正在评估事件流的哪个阶段。

e.eventPhase取值:

  • Event.NONE:0
  • Event.CAPTURING_PHASE:1
  • Event.AT_TARGET:2
  • Event.BUBBLING_PHASE:3

在事件处理程序中,点击红色方块,你应该看到e.eventPhase == 2,点击黄色方块应该看到e.eventPhase == 3

所以,下面的任一会给出预期的效果:

$(".outerbox").click(function(e) { 
    if(e.eventPhase !== Event.BUBBLING_PHASE) { 
     // here, clicks on any of the target's child elements are excluded. 
     alert("Red has been clicked, but not the yellow area"); 
    } 
}); 

$(".outerbox").click(function(e) { 
    if(e.eventPhase === Event.AT_TARGET) { 
     // here, clicks on any of the target's child elements are excluded. 
     alert("Red has been clicked, but not the yellow area"); 
    } 
}); 

因此,您可以编写代码,以筛选出任意数量的后代元素的点击,不甚至知道他们的类/ ids。

DEMO