Home >Web Front-end >JS Tutorial >How Can I Pass Arguments to an Event Listener Function in JavaScript?
Consider this scenario:
var someVar = some_other_function(); someObj.addEventListener("click", function(){ some_function(someVar); }, false);
The issue here is that someVar is not accessible within the listener function of addEventListener. It's treated as a new, local variable.
Instead of trying to access variables from outside the listener function, retrieve the arguments directly from the event target's attributes.
For instance:
const someInput = document.querySelector('button'); someInput.addEventListener('click', myFunc, false); someInput.myParam = 'This is my parameter'; function myFunc(evt) { window.alert(evt.currentTarget.myParam); }
HTML:
<button class="input">Show parameter</button>
This approach ensures that the necessary information is encapsulated within the event object, making it accessible when the listener function is invoked.
The above is the detailed content of How Can I Pass Arguments to an Event Listener Function in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!