In jQuery, the .click event handler allows you to execute a function when an element is clicked. To use this functionality, specify a function as an argument to .click(). However, encountering difficulties in passing parameters to the function is commonly faced.
To resolve this issue, you could consider using anonymous functions that immediately execute within .click(), as seen below:
<code class="js">$('.leadtoscore').click(function() { add_event('shot'); });</code>
Alternatively, if you desire to call the add_event function from multiple locations, another approach is to use jQuery's data attribute to pass parameters. Version 1.4.3 introduced this feature, allowing the creation of a data map and passing it as the first parameter to .click().
<code class="js">$('.leadtoscore').click({ event: 'shot' }, add_event);</code>
Within the event handler, access the data map via the event object, as demonstrated here:
<code class="js">function add_event(event) { const eventParam = event.data.event; }</code>
This method provides a convenient mechanism for passing parameters to functions invoked by .click() while maintaining the flexibility of calling the function from different places in your code.
The above is the detailed content of How to Pass Parameters to User Functions in jQuery .click Event Handler?. For more information, please follow other related articles on the PHP Chinese website!