Reputation: 10961
The following code renders 3 buttons with label "1", "2" and "3". Clicking on each button will alert the label.
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script type="text/javascript">
$(function() {
var a = [1, 2, 3];
$.each(a, function(i, ai) {
$('<button />').text(i).appendTo('body')
.click(function() {alert(i);});
});
});
</script>
</head>
<body>
</body>
</html>
However, if I replace function() {alert(i);}
with foo
and define function foo() { alert(i); }
, I will get an error of variable i is not defined
.
So how to pass parameters (other than event) to event handlers? I think defining the event handler (foo()
in this case) as a named function will make the code cleaner if the event handler is long and complicated.
Upvotes: 2
Views: 1701
Reputation: 112827
If you look at the documentation for bind
, you'll see it has an optional eventData
parameter. So for example this would work:
function foo(e)
{
alert(e.data.theI);
}
$(function ()
{
var a = [1, 2, 3];
$.each(a, function (i, ai)
{
$('<button/>').text(i).appendTo('body').bind("click", {theI: i}, foo);
});
});
Upvotes: 4
Reputation: 38140
$(function() {
var a = [1, 2, 3];
$.each(a, function(i, ai) {
$('<button />').text(i).appendTo('body')
.click(function() { foo.apply(this,[i]);});
});
});
function foo( i )
{
alert( i + " : " + $(this).text() );
}
Upvotes: 3
Reputation: 14526
A third method, and the way I usually do it is to invoke a function that returns your handler. Like this:
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script type="text/javascript">
var bindFoo = function(x) {
return function() {alert(x);};
};
$(function() {
var a = [1, 2, 3];
$.each(a, function(i, ai) {
$('<button />').text(i).appendTo('body')
.click(bindFoo(i));
});
});
</script>
</head>
<body>
</body>
</html>
I'm using x
in the binding function only to distinguish it from i
in the main code block.
Upvotes: 2