2012-03-19 36 views
3

我正在尋找更好的方法將多個事件綁定到jQuery中的單個元素。我試圖避免寫多個$(元素).bind('event',...)或$(element).event(...)語句。在jQuery中綁定事件的更好方法

代碼

// old way  
var textbox = $('input'); 
$(textbox).focus(function() { ... } 
$(textbox).blur(function() { ... } 

// new way 
$(textbox).extend({ 
    focus: function() { 
      ... 
    }, 
    blur: function() { 
      .... 
    } 
}); 

不幸的是,這個實現是行不通的。有沒有人有更好的建議?謝謝。

+0

它是如何工作的? – 2012-03-19 14:51:49

+1

看看['.on()'](http://api.jquery.com/on/)。 – bfavaretto 2012-03-19 14:52:00

+1

@AbeMiessler,他的「新方式」,它不工作,因爲他試圖用事件後命名的方法擴展jQuery對象。但是,這不會綁定事件。 – bfavaretto 2012-03-19 14:53:02

回答

9

到目前爲止的所有答案都假設您想要將相同的回調函數綁定到多個事件。如果不是這種情況,請考慮在活動地圖中使用.on()

$('selector').on({ 
    focus: function(e) { 
     // do something for focus 
    }, 
    blur: function(e) { 
     // do something else entirely for blur 
    }, 
    ... 
} 
+0

謝謝!這是我需要的。 – mavame 2012-03-19 15:52:01

+0

其實,幾個答案解釋瞭如何做到這一點(包括我的),只是以不同的方式(使用'e.type')。這實際上是我的首選方法,因此可以在處理程序之間輕鬆共享通用元素或邏輯。 – 2012-03-19 18:58:03

3

試試這個:

$("textbox").bind('focus blur', function() { 
    // your code 
}); 

的jQuery 1.7+ bind已被on所取代:

$("textbox").on('focus blur', function() { 
    // your code 
}); 

在這兩種情況下,指定的功能將在中列出的所有事件中運行第一個參數。

3

使用jQuery的.on()方法:

$('input').on("focus blur", function() { 
}); 

如果您需要根據事件的執行條件邏輯:

$('input').on("focus blur", function (e) { 
    var whichEvent = e.type; // Will be "focus" or "blur" 
}); 
0

您可以使用

<element>.on("eventhandlers as commaseparated list",function(){})

,如果你能對所有這些處理程序使用一個函數,或

element.click(...) 
     .<anotherhandler>(...) 
     .<yetanother>(...) 

如果您需要不同的功能。

.on()雖然是首選的方式。

0
// My way 
var textbox = $('input'); 
$(textbox).on('focus blur', function(e){ 
    if (e.type == 'focus'){ 
    // do the focus stuff 
    } else if (e.type == 'blur'){ 
    // do the blur stuff 
    } 
} 

這是未經測試,但原則持有

0

可以讓你在jQuery中使用綁定功能:

例:

$(textbox).bind('focus blur',function(){ 
    //do something 
}); 
0

一旦您保存了一個jQuery對象在一個變量中,你不需要不斷地將它轉換成一個jQuery對象反覆。你也可以「鏈接」你的事件綁定,因爲它們返回原始對象。

嘗試是這樣的:

var $textbox = $('input'); // (Use a $ to mark variables that hold jQuery objects 
$textbox 
    .on("focus", function() { ... }) 
    .on("blur", function() { ... }); 

(此外,請務必檢查您使用正確的事件名稱......我不知道多少時間,我已經浪費了那名獵錯誤因爲我爲一個事件編了自己的名字。)