0

I have a simple problem with the jQuery click event, which I am not able to solve.

Here is the code:

$('document').ready(function() {
    var links = $('.brandLinks li a');
    console.log(links.length); // there are total 24 items are there

    for(var i = 0; i < links.length; i++) {
        links[i].click(function(e){
            console.log('click.');
        });
    }
});
Littm
  • 4,923
  • 4
  • 30
  • 38
naresh kumar
  • 2,165
  • 3
  • 19
  • 21

4 Answers4

6

You don't need to loop. The majority of jQuery methods will operate on each item in the matched set. Also, document shouldn't be quoted. You want to select the actual document object. If it's quoted, jQuery will be looking for an element with the tag name "document":

$(document).ready(function() {
    $('.brandLinks li a').click(function () {
        console.log('click');
    });
});

Side note: It doesn't actually matter that the string "document" won't match anything in this case. The ready method will operate on any jQuery object, regardless of what it contains (even if it's empty). It would make much more sense to others reading your code (and yourself in the future) to actually select the document object though. For these reasons, I usually use the alternative form:

$(function () {
    // This is the same as $(document).ready(function () {});
});
James Allardice
  • 164,175
  • 21
  • 332
  • 312
0

You do not need for loop to bind event. you can bind entire elements at once. link[index] is native JavaScript element. You should have used $(link[k]).click.

$(document).ready(function() { 
    var links = $('.brandLinks li a'); 
        console.log(links.length); // there are total 24 items are there 
    links.click(function(){
           console.log('click.'); 
    });         
}); 
Anoop
  • 23,044
  • 10
  • 62
  • 76
0

Try this

$(document).ready(function() {
var links = $('.brandLinks li a');
console.log(links.length); // there are total 24 items are there

for(var i = 0; i < links.length; i++) {
    links[i].click(function(e){
        console.log('click.');
    });
}
});
iJade
  • 23,144
  • 56
  • 154
  • 243
0

The issue with your code was that you were not taking care of closure, check this

Following should work:

var link = links[i];
 $(link).click((function(value) {
                    return function() {
                      //   
                    };
                })(link));
Community
  • 1
  • 1
Anshu
  • 7,783
  • 5
  • 31
  • 41