Simple loop iterator in jQuery -
a simple question. how can make following script in simple for loop:
jquery(document).ready(function(){ jquery("#toggle-0").click(function(){ jquery("#toggle-list-0").slidetoggle(500); }); jquery("#toggle-1").click(function(){ jquery("#toggle-list-1").slidetoggle(500); }); jquery("#toggle-2").click(function(){ jquery("#toggle-list-2").slidetoggle(500); }); });
the for loop intended in python:
for in range(3): a, b = "#toggle-" + str(i), "#toggle-list-" + str(i)
thanks!
your code violates dry principle.
- there no need have 1 separate
ready
block each event handler. - you should consider using classes , class selector instead of id selectors , use power of dom traversing methods of jquery selecting target elements.
- using loop here bad option/not necessary. jquery methods have been designed iterate through collection behind scenes.
here example using comma separated selector:
jquery(document).ready(function($){ $("#toggle-0, #toggle-1, #toggle-2").click(function() { var num = this.id.replace('toggle-', ''); $("#toggle-list-" + num).slidetoggle(500); }); });
the above snippet 1 way of minifying original code imagine want add 10 more ids selector. code not maintainable , doesn't make sense. use classes instead.
Comments
Post a Comment