2011-09-04 52 views
3

我有一個#容器和按鈕,它們是此容器的子項。當我單擊容器本身(按鈕周圍的空白區域)時,我希望它改變其背景顏色,但是當單擊按鈕時我不想發生任何事情。只選擇父項,排除其他所有項,然後單擊()

選擇jQuery中的#container的,雖然,使得點擊按鈕改變BG以及...

<div id="container"> 
    <div class="button> 
     <span class="text">Button 1</span> 
    </div> 
    <div class="button> 
     <span class="text">Button 2</span> 
    </div> 
</div> 

$("#container").click(function() { 
    $('#container').css({background: 'blue'}); 
}); 

我試過很多事情,似乎沒有任何合作。當點擊event.target

回答

9

檢查事件的原始目標:

$("#container").click(function(event) { 
    if(event.target === this) { 
     $('#container').css({background: 'blue'}); 
    } 
}); 

參考

$("#container").click(function(event) { 
    if(event.target.id === "container") { 
     $('#container').css({background: 'blue'}); 
    } 
}); 
0

檢查ID,這樣你就不會拿起按鈕:

0

一個簡單 另一種解決方案:

$('#container button').click(function(event) { 
    event.stopPropagation(); 
}); 
+0

這似乎並不奏效,說不上來,如果我'不是做錯了。 – Dwelle

相關問題