0

Let's say I have a for loop dynamically generating Jquery functions - like so:

 function addJqueryFunctions(divListJSON) {
    for(var i in divListJSON)
    {
        var id = divListJSON[i].id;

        $('#' + id + ').magicfunction();
    }
}

How do I make it so that the Jquery functions generated in the for loop make it to the page and are run?

zacran
  • 855
  • 6
  • 18

1 Answers1

1

To select an element by ID, you need to prefix it with #

$('#' + id).magicFunction();

Notice that the variable and + operator have to be outside the quotes.

Barmar
  • 741,623
  • 53
  • 500
  • 612
  • Left the prefix out in the original post, but will functions work if generated in a loop? I.e. $('#id').draggable – zacran Aug 27 '14 at 21:45
  • You're not "generating" anything, you're just calling a function. And each time, you're calling it with a different context parameter. – Barmar Aug 27 '14 at 21:47
  • Your modified question has an extra quote before `)`. If you have that in your actual code it will report a syntax error. – Barmar Aug 27 '14 at 21:48
  • There are some issues with generating closures in `for` loops. See http://stackoverflow.com/questions/1451009/javascript-infamous-loop-issue. But you don't have anything like that in your question. – Barmar Aug 27 '14 at 21:49