2013-02-20 33 views
1

我写了JS函数,它必须绑定它生成的按钮,这取决于数组中的值。 但它给了我最后的价值。我读到我必须使用闭包,我做了,而且我仍然无法将它们绑定到正确的位置! 我还是一个初学者 我了解封,给我的想法,但仍然不知道我失踪不能使用Closure权利

function addNewServices(newServicesArray){ 
    var j=0; var x; 
    for (i in newServicesArray){ 
     var html=''; 

     html='<div style="width: 33%; float: leftt"><a href="#" data-role="button" data-icon="home" id="btn-'+newServicesArray[j].servicename+'" value="'+newServicesArray[j].servicename+'" class="ui-btn-up-c">'+newServicesArray[j].servicename+'</a></div>'; 
     $("#main-menu").append(html); 


     $('#btn-'+newServicesArray[j].servicename).bind('click', function(){bindThis(j)}); 
     j++; 
    } 

    var bindThis = function(j) { 
     return function() { 
      alert(j); // gives 2 always 
      alert(newServicesArray[j].servicename); 
     }; 
    }; 
} 
+1

使用jQuery的'$ .each'迭代,您可以更轻松...... – elclanrs 2013-02-20 09:09:01

+0

你不应该申报'bindThis'内循环。为什么你声明x并且从不使用它? – fragmentedreality 2013-02-20 09:16:10

+0

@fragmentedreality实际上,bindThis在循环内部是* not *声明的。 – Christoph 2013-02-20 09:28:42

回答

1

你不必绑定在点击一个循环...你可以通过在函数$(this)获得点击refrence ..

使得它作为简单的,因为我可以..

function addNewServices(newServicesArray){ 
    var j=0; 
    for (i in newServicesArray){ 
     var html=''; 

     html='<div style="width: 33%; float: left"><a href="#" data-role="button" data-icon="home" id="btn-'+newServicesArray[j].servicename+'" value="'+newServicesArray[j].servicename+'" class="ui-btn-up-c">'+newServicesArray[j].servicename+'</a></div>'; 

     $("#main-menu").append(html); 


    } 
} 

$(function(){ 
    $(document).on('click','a[id^="btn-"]',function(){ 
     var $this = $(this); 
     alert($this.attr('value')); 
    }); 
}); 
1

因为你有

function(){bindThis(j)} 

它得到后来被称为当j的值为2

你只需要

bindThis(j) 

都会调用不同取值

+2

这是一个无关的错误... – Christoph 2013-02-20 09:15:42

1

Closure只是函数从外部范围访问变量的方式。这里的关键词是变量 - 变量可能会改变,如果您之后访问它(点击),您将访问它的更高版本。

所以,无论如何,你需要的j该关联存储与j个按钮。感谢jQuery,bind方法已经有一个功能:second parameter,eventData是一些用户数据,它将被传递给事件处理函数。

因此,改变这种:

(..).bind('click',function(){bindThis(j)}); 

这样:

(..).bind('click', j, bindThis); 

...应该*工作。请注意,我们不需要创建任何包装函数。我们只需将bindThis函数本身传递给bind,并告诉bind它将在调用它时将j传递给它。

(*) - 尚未测试