[英]How can i know which element activated a click event in javascript?
I have a website and i want to execute the same action when two buttons are clicked.我有一个网站,我想在单击两个按钮时执行相同的操作。 I tried creating one single function that would be called by each button by using
.addEventListener ("click",function())
我尝试使用
.addEventListener ("click",function())
创建一个函数,每个按钮都会调用该函数
But i wonder is there a way to know which button called it?但我想知道有没有办法知道调用它的是哪个按钮? for example if i wanted to add a condition inside the function that takes a decision depending on which element called it?
例如,如果我想在函数中添加一个条件,该条件根据调用它的元素做出决定?
when you pass the function, it receives an event.当您传递函数时,它会收到一个事件。 That event holds a PointerEvent , so that type is an object with many properties of the element, one of them is
target
, and the target can get the id of each element like so:该事件包含一个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>
You can also add event listeners dynamically to the buttons like so:您还可以像这样动态地向按钮添加事件侦听器:
<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
s are useful for this (as Juliano points out). id
对此很有用(正如 Juliano 指出的那样)。 Alternatively you could add a descriptive data attribute to each button to identify it (here I've used type
).或者,您可以向每个按钮添加一个描述性数据属性来识别它(这里我使用了
type
)。 In the handler you can destructure the type
from the button's dataset, and then do x depending on its value.在处理程序中,您可以从 按钮的数据集中解构
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.