Hi StackOverflow community. I have a question about alternatives to adding JavaScript in the href of HTML anchor tags. I already know this is poor practice and instead of doing this:
<div id="some_div"><a href="JavaScript:myfunction();">Text</a></div>
I can just do this: Text
$('#some_div').on("click","a",function(e){
myFunction();
});
My question is, how does this work if you have to pass variables into the function? For example:
<div id="some_div"><a href="JavaScript:myfunction('param1','param2')">Text</a></div>
Now keep in mind that the data in param1 and param2 will be different strings. How do you handle this case? The event listener needs to receive different data entered by the anchor tag. So how would the user add the param1 and param2 data when they use:
<div id="some_div"><a href="#">Text</a></div>
Thank you in advance.
There are a lot of ways you can do it. One that comes to mind would be to use data-*
attributes on the anchor:
<a href="#" data-param1="param1" data-param2="param2">Text</a>
var $this = $(this);
myFunction($this.data("param1"), $this.data("param2"));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With