isar isar - 1 year ago 62
jQuery Question

Simple loop iterator in jQuery

A really simple question. How can I make the following script in a simple for loop:


The for loop is intended as in Python:

for i in range(3): a, b = "#toggle-" + str(i), "#toggle-list-" + str(i)


Answer Source

Your code violates the DRY principle.

  1. There is no need to have one separate ready block for each event handler.
  2. You should consider using classes and a class selector instead of the ID selectors and use the power of DOM traversing methods of jQuery for selecting the target elements.
  3. Using a loop here is a bad option/not necessary. Most jQuery methods have been designed to iterate through the collection behind the scenes.

Here is an example using a comma separated selector:

    $("#toggle-0, #toggle-1, #toggle-2").click(function() {
        var num ='toggle-', '');
        $("#toggle-list-" + num).slideToggle(500);

The above snippet is one way of minifying the original code but imagine you want to add 10 more IDs to the selector. Now you code is not maintainable and doesn't make any sense. Use classes instead.