设置与 jquery click 函数一起使用的变量
如果这只是另一个被一遍又一遍地问的问题,我很抱歉。我发现了一些类似的问题,这些例子并没有让我准确地到达我需要的地方。这类似于 jQuery 闭包、循环和事件。
$('a.highslide').each(function() {
hsGroup = $(this).attr("rel");
if(hsGroup.length > 1){
hsGroup = hsGroup.replace(/\s/g , "-");
}
this.onclick = function() {
return hs.expand(this, { slideshowGroup: hsGroup });
}
});
这段代码设置了一个 onclick 来启动一个 highslide 弹出窗口。我添加了 SlideshowGroup 属性和其上方的 hsGroup 代码,该代码提取 Rel 属性的内容来定义每个属性的组。您可能会立即看到的问题是 hsGroup 的内容不是该匿名函数的本地内容。因此,在运行时,对于应用到的每个链接,其值始终相同。我已经浏览了一些关闭示例,但迄今为止未能使它们在我的情况下工作。
谢谢,
My apologies if this is just another question that gets asked over and over. I've found some similar questions, the examples just haven't gotten me exactly where I need to be. This is similar to jQuery Closures, Loops and Events.
$('a.highslide').each(function() {
hsGroup = $(this).attr("rel");
if(hsGroup.length > 1){
hsGroup = hsGroup.replace(/\s/g , "-");
}
this.onclick = function() {
return hs.expand(this, { slideshowGroup: hsGroup });
}
});
this code setsup an onclick that launches a highslide popup. I've added the slideshowGroup property and the hsGroup code above it which pulls the contents of the Rel attribute to define the group of each. The issue as you may see right away is the contents of hsGroup is not local to that anon function. So at run time its value is always the same for each link the is applied to. I've looked through some closure examples but have thus far failed to make them work in my situation.
Thanks,
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您只需要一个
var
来为每个链接创建它,如下所示:没有
var
您将拥有一个全局hsGroup
每个循环都会重复使用的变量,并最终得到每次点击中使用的相同的最后一个值。或者,只需在
click
事件发生时进行替换,如下所示:You just need a
var
to make it per link, like this:Without the
var
you have one globalhsGroup
variable that's getting reused for every loop, and ending up with the same, last value used in every click.Or, just do the replacement at the time of the
click
event, like this:这是因为您没有将
hsGroup
声明为本地,所以缺少var
:否则,
hsGroup
是全局的,因此设置为以下值最后一次迭代。It is because you don't declare
hsGroup
as local, you are missingvar
:Otherwise,
hsGroup
is global and therefore set to the value of the last iteration.