以下代码呈现3个带有标签“1”,“2”和“3”的按钮。点击每个按钮将提醒标签。如何将参数(事件除外)传递给事件处理程序?
<!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>
但是,如果我有foo
取代function() {alert(i);}
和定义function foo() { alert(i); }
,我会得到的variable i is not defined
错误。
那么如何将参数(事件除外)传递给事件处理程序?我认为定义事件处理程序(在这种情况下为foo()
)作为命名函数将使代码更清洁,如果事件处理程序很长并且很复杂。
它不应该是'foo.call'? 'apply'接受一个数组。 – 2010-09-22 06:47:33
@Matthew Flaschen:thx - 我修正了这个问题。 – jantimon 2010-09-22 06:49:47
为什么要创建一个数组? 'foo.call(this,i);'会简单一点。 – 2010-09-22 07:12:05