目前我有一個包含兩個( )影像的 div 元素。一張圖片的 z-index 為 1,位于另一張圖片的后面。當您僅單擊第一張影像時,我想觸發事件偵聽器。
當我單擊 z-index 為 2 的較小影像時,會發生 z-index 1 影像的事件偵聽器。網站鏈接:hi2.aisliniscool.repl.co 相關JS代碼:
const champDiv = document.createElement('div');
const champImg = document.createElement('img'); //(z-index 1)
const favButton = document.createElement('img');
champDiv.addEventListener('click', toggleDiv);
favButton.addEventListener('click', favoriteChamp); //(z-index 2)
favButton.addEventListener('click', setCookie);
favButton.src = "/ext/icons/transparent.png";
favButton.classList.add('favButton');
champDiv.classList.add('champdiv');
champImg.classList.add('champion');
如果我點擊 favButton,toggleDiv 和 favoriteChamp 就會執行,但我只想讓 favoriteChamp 執行。
uj5u.com熱心網友回復:
你有冒泡的問題。
當您觸發他們的孩子事件時,您需要阻止他們觸發父母的事件。
你要么會需要這個:
event.stopPropagation()
或這個:
event.stopImmediatePropagation()
要完全理解發生了什么以及如何處理傳播,您可以閱讀以下內容:
https://javascript.info/bubbling-and-capturing
https://www.freecodecamp.org/news/event-propagation-event-bubbling-event- catch-beginners-guide/
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/527443.html
上一篇:如何在Python中使用Selenium在不重繪DOM的情況下更新多個頁面元素以避免StaleElementReferenceException?
