简体   繁体   中英

How do I pass parameters into a jQuery.click() function on a <span> tag?

I have used the jQuery.click() function in the past with buttons and have had nothing but success, but I tried to use it to click on a <span> 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 codepen.io here:

Codepen Weather App

I appreciate the help!

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() {
  console.log('Hurra!')
}

$('#example').click(MyFunction)

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

Try it like this:

 $('#example').click(bleepme); function bleepme(){ alert('hi'); }
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <p><span id="example">Click Here</span></p>

Note that the on-click call to the bleepme function does not have parens -- if you put parens there, it will run the function at document.ready, but not upon click.

Example - no parens on click

Example 2 - parens on click

Well you should supply a body to the function :)

$("#example").click(function() {
    alert('clicked');
});

I don't think that you really want to pass parameters into into the function. By the time someone is clicking on the temperature to toggle the units, the document.ready function has finished executing. You actually want to read the values for temp and units from the DOM or from local storage. So, you don't need to pass parameters into your function, which should make things a bit easier.

I think you code need to work like this way

$(document).ready(function(){
  $('#example').on('click',function(){
    // Some of your logic here
  });
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM