这并不完全清楚你的要求,但是......无论如何,我会采取刺的方式。这听起来像你基本上想要扩大传递给事件处理程序的事件数据。有许多方法可以做到这一点:
如果您正在使用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