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
2 Answers
Reset to default 8Say 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
版权声明:本文标题:javascript - Pass a parameter to a event handler in jQuery - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741638978a2389803.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论