简体   繁体   中英

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())

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:

<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). Alternatively you could add a descriptive data attribute to each button to identify it (here I've used type ). In the handler you can destructure the type from the button's dataset, and then do x depending on its value.

 // 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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM