我有我的HTML設置是這樣的:jQuery的點擊李
<li>
Header
<button>Edit</button>
</li>
,我想知道如果有一種方法讓你可以在李點擊,並有一個動作發生,單擊按鈕併發生另一個行動。現在,如果我在jQuery上有一個jQuery點擊元素,它會在您點擊按鈕時觸發。有沒有辦法在不改變html結構的情況下做到這一點?
我有我的HTML設置是這樣的:jQuery的點擊李
<li>
Header
<button>Edit</button>
</li>
,我想知道如果有一種方法讓你可以在李點擊,並有一個動作發生,單擊按鈕併發生另一個行動。現在,如果我在jQuery上有一個jQuery點擊元素,它會在您點擊按鈕時觸發。有沒有辦法在不改變html結構的情況下做到這一點?
也可以使用event target
。
$('li').click(function(event) {
var $tgt=$(event.target);
if($tgt.is('button')){
alert('button clicked');
}else{
alert('li clicked');
}
});
按鈕單擊事件處理程序中使用event.stopPropagation() - 這將向上冒泡到li
button.click(function(event){
event.stopPropagation();
});
是停止的情況下,你可以在處理器使用event.stopPropagation的按鈕:
$(document).ready(function() {
$('li').click(function() {
alert('li clicked');
});
$('button').click(function(event) {
event.stopPropagation();
alert('button clicked');
});
});
演示:jsfiddle
向我們展示您使用的JQuery代碼,因爲它們在兩者上都必須是錯誤的。 – webnoob