我的頁面上有一個非常基本的Bootstrap按鈕。我有一個事件監聽器正在監聽點擊這個按鈕。我有一個圖像標籤作爲按鈕的內容。當用戶點擊按鈕時,事件監聽器根據需要觸發。但是,如果按鈕點擊落在按鈕內的圖像上,則圖像會攔截點擊並且按鈕點擊事件偵聽器不會觸發。我怎樣才能讓按鈕檢測點擊它本身及其內容(例如圖片標籤)?按鈕點擊按鈕內容攔截的事件
<button type="button" class="btn btn-custom" id="navLogoButtonLeft">
<!-- dev tools indicate clicks land on this <img> and never make it to the <button> -->
<img class="icon" src="img/icon.png">
</button>
請注意,這是一個Twitter Bootstrap按鈕,但我不確定是否對此問題有任何影響。
這裏是JS,請求。
var navLogoButtonLeft;
function initNav() {
navLogoButtonLeft = document.getElementById('navLogoButtonLeft');
// note, I've tried both 'true' and 'false' here
navLogoButtonLeft.addEventListener('click', handleClick, true);
}
// this method does fire, but clickEvent is the <img>, not the <button>
function handleClick(clickEvent) {
if(clickEvent.target == navLogoButtonLeft) {
// this line cannot be reached
window.location = './';
return;
}
}
window.addEventListener('load', initNav, false);
請發佈[mcve],包括您的JavaScript – j08691
JavaScript與HTML不匹配。請閱讀@ j08691鏈接的頁面上的完整內容。 –