2010-09-22 145 views
2

以下代码呈现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())作为命名函数将使代码更清洁,如果事件处理程序很长并且很复杂。

回答

3
$(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()); 
} 
+0

它不应该是'foo.call'? 'apply'接受一个数组。 – 2010-09-22 06:47:33

+0

@Matthew Flaschen:thx - 我修正了这个问题。 – jantimon 2010-09-22 06:49:47

+0

为什么要创建一个数组? 'foo.call(this,i);'会简单一点。 – 2010-09-22 07:12:05

2

第三种方法,我通常做的方法是调用一个返回你的处理函数的函数。就像这样:

<!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> 

我在结合功能使用x只从i在主代码块区分开来。

4

如果你看看the documentation for bind,你会发现它有一个可选的eventData参数。因此,例如,这将工作:

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); 
    }); 
}); 
相关问题