admin管理员组

文章数量:1296457

How I send to the handler a variable that's on the outer scope?

i = 1;
$(id).change(function() {myHandler(i)});
i = 2;

When called, the parameter is 2.

Also tried as string, that work in DOM but dont work in jQuery:

$(id).change('myHandler(' + i + ')');

How I send to the handler a variable that's on the outer scope?

i = 1;
$(id).change(function() {myHandler(i)});
i = 2;

When called, the parameter is 2.

Also tried as string, that work in DOM but dont work in jQuery:

$(id).change('myHandler(' + i + ')');
Share Improve this question asked Jul 31, 2012 at 0:33 arielariel 16.1k13 gold badges64 silver badges75 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 8

Say you want to pass data object,

var data = {i: 2};
$(id).change(data, myHandler);

In the myHandler function:

function myHandler(event) {
    var i = event.data.i; // <= your data
}

The value passes as parameter if modified later wont get reflected.

By calling a function that accepts i as an argument and returns a function, you can make a closure that traps the current value of i.

function changeHandlerClosure(i) {
    return function() {
        //do stuff here with i
    };
}

i = 1;
$(id).change(changeHandlerClosure(i));
i = 2;

This avoids interacting with the DOM, which is sometimes more convenient but slower.

本文标签: javascriptPass a parameter to a event handler in jQueryStack Overflow