Eric Stermer Eric Stermer - 2 years ago 81
jQuery Question

How do I pass parameters into a function on a <span> tag?

I have used the function in the past with buttons and have had nothing but success, but I tried to use it to click on a and it doesn't work.

Also I noticed that it automatically executed my function without listening to the click.

Judging how I used it on buttons, this would be the syntax:

<p><span id="example">Click Here</span></p>

$("#example").click(exampleFunction(p1, p2));

But it does not seem to work. Again it just executes it without the click even taking place. I even tried:

$(document).on("click", "#example", exampleFunction(p1, p2));

Still no luck, same results.

I am making a weather app and my goal with this is to toggle the temperature between Fahrenheit and Celsius by clicking on the unit. I made a copy of the code for the app on here:

Codepen Weather App

I appreciate the help!

Answer Source

Looks like you should try something like this:

$(document).on("click", "#example", function() {
  console.log('Hello World');

Using the function() definition alone give me Uncaught SyntaxError: Unexpected token (.

What you're doing is binding an anonymous function to the click. If you were doing this somewhat differently, like MyFunction(), then it would only execute the function.

If you had MyFunction you could still trigger it using click like so:

function MyFunction() {


Notice that I didn't use the parentheses otherwise it will actually run the function instead of binding it.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download