我写了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);
};
};
}
使用jQuery的'$ .each'迭代,您可以更轻松...... – elclanrs 2013-02-20 09:09:01
你不应该申报'bindThis'内循环。为什么你声明x并且从不使用它? – fragmentedreality 2013-02-20 09:16:10
@fragmentedreality实际上,bindThis在循环内部是* not *声明的。 – Christoph 2013-02-20 09:28:42