這並不完全清楚你的要求,但是......無論如何,我會採取刺的方式。這聽起來像你基本上想要擴大傳遞給事件處理程序的事件數據。有許多方法可以做到這一點:
如果您正在使用jQuery:
首先,bind()
方法可以用2個或3個參數來調用:
bind(eventName , eventHandler)
bind(eventName , data , eventHandler)
如果使用3個參數調用bind()
,則第二個參數data
,是傳遞給事件處理程序的任意對象,作爲傳遞給事件處理程序的Event
實例的.data
屬性。其次,事件處理程序是一個閉包,它的詞法範圍包括那些在創建閉包時處於範圍內的變量。舉例來說,你會一個事件處理程序綁定到jQuery的事件通常的方式是這樣的:
$(function(){
var pi = 3.1415926 ;
var phoneticAlphbet = { a = "alpha" , b = "bravo" , c = "charlie" ,
...
x = "x-ray" , y = "yankee" , z = "zulu"
} ;
$('input:radio[name=buttonset1]').click(function(){
// at this point, the variables pi and phonetic alphabet are in-scope,
// as well as any other globals you've created
// do something here
}) ;
}) ;
所以這就是將數據傳遞到事件處理程序的第二種方式。
第三種方法是將數據從DOM樹元素中掛起。 jQuery的方便提供了data()
方法做到這一點:
.data(name , value)
設置在纏繞的值設置
.data(name)
檢索來自包裝值設定
例如,該片段將保存原始值對於頁面上的每個和元素:
$('input,select').each(function(){
var item = $(this) ;
item.data('original-value' , item.val()) ;
}) ;
設置它後,可以檢索該值:
$('input#password').change(function(){
var item = $(this) ;
var oldValue = item.data('original-value') ;
var newValue = item.val() ;
if (oldValue == newValue)
{
alert('the new password must be different than the old password!') ;
}
}) ;
謝謝!這是相當的教訓:) – KTProg 2011-04-29 20:11:38