Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to dynamically change a parameter of a javascript call from the href attribute of an element

Is there a way to dynamically change what parameters are passed to a javascript function from an html element? For instance, say I have the following:

<a id="myElement" href="javascript:myFunction('myParam');">Click me!</a>

How can I change 'myParam' to another parameter, say 'myParam2'? An answer using either javascript or jquery is fine with me. For simplicity's sake, feel free to suppose I can find this element by document.getElementById('myElement') or some other means.

like image 873
Tony Wickham Avatar asked Dec 12 '25 21:12

Tony Wickham


1 Answers

What I would do instead is bind a click handler and use this to figure out which was clicked.

$('#myElement').click(function () {
    console.log($(this).text()); // Should dump "Click me!" to the console.
});

You could then add attributes to your links, such as data-someParam="my value" and access them with .attr().

like image 61
Brad Avatar answered Dec 15 '25 10:12

Brad



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!