我需要使用绑定click
事件到DOM中的一个元素,同时能够传递参数,包括事件对象。我现在的脚本使用下列内容:将参数传递给jQuery .click WHILST保留事件参数
var counter = 1;
$(".dynamo_user_info .dynamo_awards").each(function(){
$(this).find("~ div a").each(function(){
var id = $(this).attr("rel").split("aid-")[1];
$(this).attr("id","dynamo_award-"+counter+"-"+id).bind('click',{c:counter,i:id},function(e){
e.returnValue = e.preventDefault && e.preventDefault() ? false : false;
dynamo.awards.tooltip.ini(c,i);
});
});
counter++;
});
现在,你可以看到,在每次迭代counter
增加,id
不持有静态值。每次迭代后,最终值为:counter = 4
,id = 2
。现在只要点击这些元素中的一个,就会根据需要preventDefaults
,然后运行dynamo.awards.tooltip.ini(c,i);
。
但是,这不符合预期。相反,它的运行:
dynamo.awards.tooltip.ini(1,1);
dynamo.awards.tooltip.ini(2,6);
等(例如),它,而不是运行:
dynamo.awards.tooltip.ini(4,2);
dynamo.awards.tooltip.ini(4,2);
即它使用counter
和id
上次存储的值。我的猜测是,这是由于bind
如何工作,传递参数时元素被点击,而不是之前。我不知道如何解决这个问题,除非我能以某种方式欺骗函数的范围?
*尽管!*啊,英文。 ':'' – 2012-08-12 22:14:53
您需要了解[闭包范围](http://stackoverflow.com/questions/111102/how-do-javascript-closures-work)。 (另见[Bonsai!](http://bonsaiden.github.com/JavaScript-Garden/#function.closures)和枯燥的旧版[MDN](https://developer.mozilla.org/en-US/docs/) JavaScript /指南/闭包)) – 2012-08-12 22:17:32
就像一个侧面说明,这条线似乎是多余的:'e.returnValue = e.preventDefault && e.preventDefault()? false:false;' – ahren 2012-08-12 22:27:39