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.