You've written a closure over the variable i
, but by the time the function executes i
has incremented past the bounds of the array. You can get around this by create a function which generates a new function, and passing in the enclosed variables as parameters to the outer function, like this:
var clickFunc = function(seek) {
return function() { widget.seekTo(seek); };
}
for (i=0; i<10; i++) {
$(goToId[i]).click(clickFunc(goToTime[i]));
}
Also, I believe you'll have to remove either the single-quotes or the double-quotes in your goToId
array:
var goToId = [ "#goTo5", "#goTo10", ... ];
// or
var goToId = [ '#goTo5', '#goTo10', ... ];
Or if you prefer, you can get rid of both your arrays entirely if you write your loop like this:
var clickFunc = function(id, seek) {
$(id).click(function() { widget.seekTo(seek); });
}
for (i = 1; i <= 10; i++) {
clickFunc("#goTo" + (5*i), 300000 * i);
}
Or to implement the solution like what net.uk.sweet hinted at, first assign a CSS class to all your #goToN
elements, say .goToButton
like this (I used <a>
elements for demonstration, but the actual type of element you use isn't important):
<a id="goTo5" class="goToButton" href="#">5</a>
<a id="goTo10" class="goToButton" href="#">10</a>
<a id="goTo15" class="goToButton" href="#">15</a>
...
Then use the jQuery each
method:
$('.goToButton').each(function(i) {
$(this).click(function() {
widget.seekTo(300000 * (i+1));
});
});
Note that this depends on the elements you're binding to being in the correct order within the document. If they are not in order, you may have to make adjustments to this script.