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.

  1. there no need have 1 separate ready block each event handler.
  2. you should consider using classes , class selector instead of id selectors , use power of dom traversing methods of jquery selecting target elements.
  3. 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

Popular posts from this blog

powershell Start-Process exit code -1073741502 when used with Credential from a windows service environment -

twig - Using Twigbridge in a Laravel 5.1 Package -

c# - LINQ join Entities from HashSet's, Join vs Dictionary vs HashSet performance -