setting variable to be used with jquery click function
My apologies if this is just another q开发者_StackOverflowuestion 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,
You just need a var
to make it per link, like this:
$('a.highslide').each(function() {
var hsGroup = $(this).attr("rel");
//^ -- add this
if(hsGroup.length > 1){
hsGroup = hsGroup.replace(/\s/g , "-");
}
this.onclick = function() {
return hs.expand(this, { slideshowGroup: hsGroup });
}
});
Without the var
you have one global hsGroup
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:
$('a.highslide').click(function() {
var hsGroup = $(this).attr("rel");
if (hsGroup.length > 1) hsGroup = hsGroup.replace(/\s/g , "-");
return hs.expand(this, { slideshowGroup: hsGroup });
});
It is because you don't declare hsGroup
as local, you are missing var
:
var hsGroup = $(this).attr("rel");
Otherwise, hsGroup
is global and therefore set to the value of the last iteration.
精彩评论