4

This function gets called on page load, not when .somebutton is clicked. I'm not sure why. I want to be able to pass the variables so that I may use this function in multiple places with different values. Thank you very much.

var i = "this be i";
var u = "this be u";

function dosomething (var1, var2){
    console.log(var1 + " and " + var2);
}

$(".somebutton").click(dosomething(i,u));
4

3 に答える 3

6

You are passing value returned by dosomething(i,u) to click handler. This is why it ise executing without clicking, it is happening as soon as you call your function (that is: dosomething(i,u)). You need to wrap your function call inside anonymous function:

$(".somebutton").click(function() { dosomething(i,u); } );
于 2013-02-08T17:17:51.820 に答える
1

You can only pass a function by reference using the method in your example (ie. without parameters). The reason your function works on load is because it is immediately invoked due to the trailing () brackets.

If you need to pass parameters you need to wrap it in an anonymous function, like this:

// on click:
$(".somebutton").click(function() {
    dosomething(i, u);
});

// on page load:
dosomething(i, u);
于 2013-02-08T17:18:23.580 に答える
1

In JavaScript doing

$(".somebutton").click(dosomething(i,u));

will not assign the function to your click event, but will rather call the function and assign whatever result the function returns. You need to reference your function instead :

$(".somebutton").click(dosomething);

If you need to pass variables to your function, then you need to wrap the said function inside another anonymous one :

$(".somebutton").click(function() { dosomething(i, u); });
于 2013-02-08T17:21:39.550 に答える