jQuery和javascript的关闭 [英] jquery and javascript's closure

查看:96
本文介绍了jQuery和javascript的关闭的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到了下面的代码,而javascript的关闭以及匿名函数使我头疼.

I am having the code below and javascript's closure together with anonymous functions are giving me a headache.

for (var i = 0, len = sites.length ; i < len ; i++)
{
  $("#thumb"+i).click(function() { $("#shader").show(); $("#thumbInfo"+i).show(); alert("#thumbInfo"+i); });
  $("#thumbInfo"+i+" .xbutton").click(function() { $("#shader").hide(); $("#thumbInfo"+i).hide(); });
}

由于关闭,我始终为5(sites数组具有5个元素),因此所有单击处理程序都引用相同的ID.

Due to closure, i is always 5 (the sites array has 5 elements), so all the click handlers refer to the same id.

有什么解决方法吗?

推荐答案

您总是可以使用jQuery的 each() .

You could always loop with jQuery's each().

$.each(sites, function(i) {
  $("#thumb"+i).click(function() { $("#shader").show(); $("#thumbInfo"+i).show(); alert("#thumbInfo"+i); });
  $("#thumbInfo"+i+" .xbutton").click(function() { $("#shader").hide(); $("#thumbInfo"+i).hide(); });
});

这篇关于jQuery和javascript的关闭的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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