2017-02-14 120 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