使用jQuery向元素添加动态函数 [英] Add a dynamic function to an element using jQuery
本文介绍了使用jQuery向元素添加动态函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试将动态.change()
函数附加到元素列表:
I'm trying to attach a dynamic .change()
function to a list of elements:
els = new Array('#element1','#element2');
for (i=1; i < 3; i++){
$(els[i]).change(function(){
alert(i);
});
}
这不能按要求工作,因为i
没有传递到函数中,而是始终等于最后一次迭代,即2.如何将值传递给change(function{})
?
This does not work as desired because i
is not passed into the function, but is instead always equal to the last iteration, ie, 2. How do I pass a value into the change(function{})
?
推荐答案
两种方法.
使用
$.each
var element_array = new Array('#element1','#element2');
$.each( element_array, function( index, value ){
$(value).change(function(){
alert( index );
});
});
创建一个闭合.
Create a closure.
var element_array = new Array('#element1','#element2');
for ( i = 0; i < element_array.length; i++){
(function(i){
$(element_array[i]).change(function(){
alert(i);
});
})(i);
}
这篇关于使用jQuery向元素添加动态函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文