Dynamically declaring jQuery functions?

Hi, I am new here and I got into using jQuery not too long ago. I have a question regarding jQuery “dynamically”. Consider the following piece of code:

jQuery(document).ready(function() {
    //Not sure if I declared this array correctly. If not, then assume that it's an array with only strings.
    var array = {"element1", "element2", "element3"};

    for (var index in array){
                    $("#" + index + " a").click(function() {
                            alert(index);
                    });
    }
});

Here I am trying to assign a click function (the alert) to all the links in the elements whose id matches those in the array. In this case, would the links in all three elements have the click function, or would only the last one have the click function? For me, the latter has been the case unless if I’m doing something wrong, but I would like clarifications and, if possible, alternative solutions as to how I can achieve the desired result. Thanks.

Those aren’t array items in the array variable, the curly braces instead define an object.

If you want them to be array items you will need to instead use square brackets:


var array = ['element1', 'element2', 'element3'];

All three elements will have the click function.

There are better ways of doing it though, by making good use of some features of jQuery.
For example, you can define those array elements as a jQuery object, and then use the each method to process them.

As it’s also more favored to use single quotes in javascript, due to how that practice tends to make your life easier when it comes to mixing in with HTML double quotes (not an issue in this case though), I’ll use single quotes in these examples.

That would be something like this, instead:


$(function () {
    $(['element1', 'element2', 'element3']).each(function () {
        $('#' + this + ' a').click(function() {
            ...
        });
    });
});

Or you could do away with the array stuff completely, and use element identifiers instead:


$(function () {
    $(['#element1, #element2, #element3']).each(function () {
        $('a', this).click(function() {
            ...
        });
    });
});