[英]How can i know which element activated a click event in javascript?
我有一個網站,我想在單擊兩個按鈕時執行相同的操作。 我嘗試使用.addEventListener ("click",function())
創建一個函數,每個按鈕都會調用該函數
但我想知道有沒有辦法知道調用它的是哪個按鈕? 例如,如果我想在函數中添加一個條件,該條件根據調用它的元素做出決定?
當您傳遞函數時,它會收到一個事件。 該事件包含一個PointerEvent ,因此該類型是一個具有元素許多屬性的對象,其中之一是target
,並且 target 可以像這樣獲取每個元素的 id :
<body>
<button id="b1">
button1
</button>
<button id="b2">
button2
</button>
</body>
<script>
const button1 = document.getElementById('b1')
const button2 = document.getElementById('b2')
const myCustomListener = function(e) {
console.log(e.target.id) // b1 or b2
}
button1.addEventListener('click', myCustomListener )
button2.addEventListener('click', myCustomListener )
</script>
您還可以像這樣動態地向按鈕添加事件偵聽器:
<body>
<button id="b1" class="button">
button1
</button>
<button id="b2" class="button">
button2
</button>
</body>
<script>
const buttons = document.getElementsByClassName('button')
const myCustomListener = function(e) {
console.log(e.target.id) // b1 or b2
}
for (let button of buttons) {
button.addEventListener('click', myCustomListener)
}
</script>
id
對此很有用(正如 Juliano 指出的那樣)。 或者,您可以向每個按鈕添加一個描述性數據屬性來識別它(這里我使用了type
)。 在處理程序中,您可以從 按鈕的數據集中解構type
,然后根據其值執行x 。
// Get the buttons const buttons = document.querySelectorAll('button'); // Add listeners to them buttons.forEach(button => { button.addEventListener('click', handleClick); }); function handleClick(e) { // Destructure the type from the button dataset const { type } = e.target.dataset; if (type === 'fruit') console.log('Banana'); if (type === 'vegetable') console.log('Potato'); }
<section class="buttons"> <button data-type="fruit">Surprise fruit!</button> <button data-type="vegetable">Surprise vegetable!</button> </section>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.