Add a dynamic function to an element using jQuery

2019-07-27 10:51发布

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);
    });
}

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{})?

4条回答
We Are One
2楼-- · 2019-07-27 11:03

Have you tried something like that:

els = new Array('#element1','#element2');

for (i=1; i < 3; i++){ $(els[i]).bind( 'change', function(){ alert(i); }); }

When you load the page, jQuery does not know the array's values and it is like a string.

查看更多
萌系小妹纸
3楼-- · 2019-07-27 11:09

jQuery events can take eventData in the signiture and pass it as arguments to your callback function. From jQuery docs:

.change( [eventData], handler(eventObject) )

What you want is this (I've changed the arg name to keep it obvious):

for (i=1; i < 3; i++){
    $(els[i]).change({index: i}, function(event){
        alert(event.data.index);
    });
}
查看更多
ゆ 、 Hurt°
4楼-- · 2019-07-27 11:22

Two ways of doing this.

Use $.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);
}
查看更多
乱世女痞
5楼-- · 2019-07-27 11:23

All of your generated functions refer to the same variable: i. This variable subsequently changes when the loop continues, so that by the time your change event fires, i will be set to 2.

You have to create a local scope that stores the value of i at the moment your function is being created:

els = new Array('#element1','#element2');

for (i=1; i < 3; i++){
    (function(i){
        $(els[i]).change(function(){
            alert(i);
        });
    })(i);
}
查看更多
登录 后发表回答