0

I made a function that sets .click for the number of buttons passed to it.

The function is called when another Jquery detects the number of buttons on the page

...
var n = $(".button").length + 1;
...
set_navig(n);
...

function set_navig(n){
    for(i=1 ; i<n ; i++){
        var btn = "#pb" + i;
        $(document).ready(function(){
            $(btn).click(function(){
                alert('Working!');
            });
        });
    }
}

I have tried removing or adding buttons on the page - correct (n) is passed to the function, but ALWAYS only the last one doesn't work at all.

ANY IDEAS?


Thnx to EVERYBODY for so much good stuff available here. You where the major source of Jquery knowledge when I started learning it.

1 Answers1

0

Well, I originally thought you should use i<=n, but you pass length + 1 (that's unusual by the way). You could just pass the button array instead of the length. Then you can iterate through each one.

I don't see a specific error with the code other than style, so perhaps you are not getting as many .button objects as you think or perhaps you have a typo in the last ID. You should paste a sample of the html code or just debug it yourself using alert() to see what values are being passed.

For future reference, common loops in many languages are either: for(i=0;i<n;i++){} or for(i=1;i<=n;i++){} I would say passing length + 1 to your function is very poor practice.

doog abides
  • 2,270
  • 16
  • 13