我有一個示例卡,里面有一個按鈕。當我點擊卡片時,會出現一條日志,表明卡片被點擊,但是當我點擊按鈕時,會出現一條日志訊息,表明我點擊了卡片和按鈕。
單擊按鈕時,它應該只顯示按鈕的日志訊息。不是卡。
如何處理這個問題?
$('.cards').on('click', function(){
console.log('click the card')
})
$('#buttonAdd').on('click', function(){
console.log('click the button')
})
.cards{
padding:20px;
background-color:grey;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="cards">
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Cupiditate, eveniet.</p>
<button id="buttonAdd">Add</button>
</div>
uj5u.com熱心網友回復:
通過單擊按鈕,您也可以單擊卡片。首先為按鈕拋出事件,然后為卡片(依次遍歷正文和 html)。如果您不希望事件傳播,請添加 event.stopPropagation() ,例如:
$('#buttonAdd').on('click', function(e){
e.stopPropagation();
console.log('click the button')
})
請注意,我已將事件引數 (e) 添加到您的函式中。
uj5u.com熱心網友回復:
只需return false在您的子函式 (#buttonAdd) 末尾添加一個以防止事件傳播。
或者,您可以添加一個event.stopPropagation()來停止事件傳播。在這里看到:jQuery stopPropagation
$('.cards').on('click', function(){
console.log('click the card')
})
$('#buttonAdd').on('click', function(){
console.log('click the button')
return false
})
.cards{
padding:20px;
background-color:grey;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="cards">
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Cupiditate, eveniet.</p>
<button id="buttonAdd">Add</button>
</div>
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/355936.html
標籤:javascript 查询
