2010-09-22 106 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); 
    }); 
}); 
相關問題