在循环中绑定事件处理程序需要关闭? [英] Closure needed for binding event handlers within a loop?

查看:122
本文介绍了在循环中绑定事件处理程序需要关闭?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在一个循环内绑定事件处理程序,例如:

  var tabs = ['one'两个','三','四'] 

for(var i = 0; i alert(tabs [i]);
var id = i;
$('#'+ tabs [i])。bind('click',function(){
loadTabs(id,tabs);
});
}

这只保留最后一个绑定(值'four' p>

我试图合并当前正常工作的代码:

  $('#one')。click(function(){
loadTabs(0,tabs);
});

$('#two')。click(function(){
loadTabs(1,tabs);
});

$('#three')。click(function(){
loadTabs(2,tabs);
});

$('#four')。click(function(){
loadTabs(3,tabs);
});

思考我可能需要一个闭包,因为此帖

解决方案

您在其他帖子
你需要一个闭包将参数绑定到每个onclick处理程序:

  $('#' tabs(i))。bind(
'click',
(function(id){
return function()
{
loadTabs
};
})(id)
);

您可能还想查看 currying
在这个例子中,你可以创建一个小助手函数,它将第一个参数绑定到一个传递的函数并返回新函数。

  function curry(func,arg1)
{
return function()
{
func(arg)
};
}

然后像这样放在一起:

  $('#'+ tabs [i])。bind(
'click',
curry(function(id){loadTabs (id);},id)
);请注意,我的curry函数不匹配currying的定义,因为它忽略任何其他参数。但它应该适合你的情况。


I'm trying to bind event handlers within a loop such as:

        var tabs = ['one', 'two', 'three', 'four']

        for(var i = 0; i < tabs.length; i++) {
            alert(tabs[i]);
            var id = i;
            $('#' + tabs[i]).bind('click', function() {
               loadTabs(id, tabs);
            });
        }

Which only keeps the last one bound (value 'four').

I'm trying to consolidate this code which currently does work:

        $('#one').click(function() {
            loadTabs(0, tabs);
        });

        $('#two').click(function() {
            loadTabs(1, tabs);
        });

        $('#three').click(function() {
            loadTabs(2, tabs);
        });

        $('#four').click(function() {
            loadTabs(3, tabs);
        });

Thought I might need a closure due to this post.

解决方案

You are right about what you read in the other post. You need to make a closure to bind the arguments to each single onclick handler:

$('#' + tabs[i]).bind(
    'click', 
    (function(id) {
        return function() 
        {
            loadTabs(id, tabs);
        };
    })(id)
);

You might also want to look into currying. In this example you might create a small helper function, which binds the first argument to a passed function and returns the new function.

function curry(func, arg1)
{
    return function()
    {
        func(arg);
    };
}

And then put it together like this:

$('#' + tabs[i]).bind(
    'click', 
    curry(function(id) { loadTabs(id); }, id)
);

Note that my curry function does not match the definition of currying, because it ignores any other argument. But it should work for your case.

这篇关于在循环中绑定事件处理程序需要关闭?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆