javascript - Writing a for loop with to create multiple methods using arrays -
i'm trying create loop reproduce following functioning block of code, in more attractive way. use soundcould widget api implementation found here on stackoverflow
$(document).ready(function() { var widget = sc.widget(document.getelementbyid('soundcloud_widget')); widget.bind(sc.widget.events.ready, function() { console.log('ready...'); });} $('#goto5').click(function() {widget.seekto(300000);}); $('#goto10').click(function() {widget.seekto(600000);}); $('#goto15').click(function() {widget.seekto(900000);}); $('#goto20').click(function() {widget.seekto(1200000);}); $('#goto25').click(function() {widget.seekto(1500000);}); $('#goto30').click(function() {widget.seekto(1800000);}); $('#goto35').click(function() {widget.seekto(2100000);}); $('#goto40').click(function() {widget.seekto(2400000);}); $('#goto45').click(function() {widget.seekto(2700000);}); $('#goto50').click(function() {widget.seekto(3000000);}); */ });
this non working attempt @ creating loop arrays write lines:
$(document).ready(function() { var widget = sc.widget(document.getelementbyid('soundcloud_widget')); widget.bind(sc.widget.events.ready, function() { console.log('ready...'); }); var gotoid = [ "'#goto5'", "'#goto10'", "'#goto15'", "'#goto20'", '#goto25', '#goto30', '#goto35', '#goto40', '#goto45', '#goto50']; var gototime = [ 300000, 600000, 900000, 1200000, 1500000, 1800000, 2100000, 2400000, 2700000, 300000]; (i=0, i<10, i++) { $(gotoid[i]).click(function() { widget.seekto(gototime[i]); }); } });
can tell me i've done wrong?
you've written closure on variable i
, time function executes i
has incremented past bounds of array. can around create function generates new function, , passing in enclosed variables parameters outer function, this:
var clickfunc = function(seek) { return function() { widget.seekto(seek); }; } (i=0; i<10; i++) { $(gotoid[i]).click(clickfunc(gototime[i])); }
also, believe you'll have remove either single-quotes or double-quotes in gotoid
array:
var gotoid = [ "#goto5", "#goto10", ... ]; // or var gotoid = [ '#goto5', '#goto10', ... ];
or if prefer, can rid of both arrays entirely if write loop this:
var clickfunc = function(id, seek) { $(id).click(function() { widget.seekto(seek); }); } (i = 1; <= 10; i++) { clickfunc("#goto" + (5*i), 300000 * i); }
or implement solution net.uk.sweet hinted at, first assign css class #goton
elements, .gotobutton
(i used <a>
elements demonstration, actual type of element 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 jquery each
method:
$('.gotobutton').each(function(i) { $(this).click(function() { widget.seekto(300000 * (i+1)); }); });
note depends on elements you're binding being in correct order within document. if not in order, may have make adjustments script.
Comments
Post a Comment