2

I have an array called print and am trying to get a seperate click event for each button that has id of the print value. Only my last button seems to work unlike the rest and I've looked through online examples and know this is a closure problem. Help is appreciated. Thanks

for(var i = 0; i < print.length; i++){
            var printer = print[i];
            // Watch this:
           $(document).ready(function(){$('#'+printer).click((function(value) {
                return function() {
                     alert(value);
                };
            })(printer));
        });
    }   
user1022570
  • 61
  • 1
  • 3
  • 7
  • 1
    `$(document).ready(function(){});` is supposed to appear only one time on each document (or at least the same namespace only once). Check the docs. Also, there are easier ways to accomplish the objective. – yoda Oct 31 '11 at 19:26
  • 2
    @yoda that is incorrect. Where do you see that in the docs? The entire point of the jQuery `ready()` function is that it can be called as many times as you want. – Jim Mitchener Oct 31 '11 at 19:35

2 Answers2

5
$(document).ready(function(){
    for(var i = 0; i < print.length; i++){
            var printer = print[i];
            // Watch this:
           $('#'+printer).click((function(value) {
                return function() {
                     alert(value);
                };
            })(printer));

    }   
})

You syntax was screwy. Your closure was perfect, but the document is only ready once.

Example

Joe
  • 80,724
  • 18
  • 127
  • 145
  • Calling $(document).ready() more than one time is not wrong. Each consecutive call will add a callback for the 'ready' state. It is just the wrong approach in this particular case. – Yuri Ghensev Oct 31 '11 at 19:33
  • Arkilus, he never stated it was wrong. I think this comment is meant for Yoda. – aziz punjani Oct 31 '11 at 19:43
  • Actually none of this will work. The correct thing to do is use the bind function along with "click" as parameter and any other arguments if needed – user1022570 Nov 03 '11 at 16:46
1

A more jQuery-ish solution would be

$(document).ready(function(){
    for(var i = 0; i < print.length; i++){
        var printer = print[i];

        $('#' + printer).click(function() {
            alert($(this).text());
        });
    }
});
Jim Mitchener
  • 8,835
  • 7
  • 40
  • 56