-2

I have something like this:

for (var i = 1; i <= numPages; i++)
{                      
    buttons.append($("<button onclick='getJSON(i)'>"+i+"</button>"));
}

Now, passing i inside getJSON() function doesn't seem to work.
Any ideas how to solve this?

Yeldar Kurmangaliyev
  • 33,467
  • 12
  • 59
  • 101
Umzea
  • 5

3 Answers3

3

Other answerers already have described how you can do this.
However, I would recommend another way:

for (var i=1; i<=numPages;i++)
{          
    $("<button/>")
        .addClass('myClass')
        .attr('data-my-id', i)
        .text(i)
        .appendTo(buttons);
}

$(document).on('click', '.myClass', function() {
    getJSON($(this).attr('data-my-id'));
});

It will generate the following HTML:

<button class='myClass' data-my-id='1'>1</button>
<button class='myClass' data-my-id='2'>2</button>
<button class='myClass' data-my-id='3'>3</button>
<button class='myClass' data-my-id='4'>4</button>
etc.

Why is this approach better?

  • Button is now generated using jQuery, but not from a string, which decreases a chance of error
  • It uses jQuery events instead of onclick attribute
  • Event delegation for convenient work with dynamically created elements
  • Element HTML doesn't contain behaviour (event) - it stores data (id)

jQuery is slower than a native JavaScript, but it is important only if we talk about thousands of elements. Otherwise, it is more important that code can be easily written, read and supported.

Also, here is a good article which describes why you shouldn't use onclick attribute`:
jQuery.click() vs onClick

Community
  • 1
  • 1
Yeldar Kurmangaliyev
  • 33,467
  • 12
  • 59
  • 101
1
buttons.append($("<button onclick='getJSON("+i+")'>"+i+"</button>"));

You need to concatenate is properly, the way you did for another i

void
  • 36,090
  • 8
  • 62
  • 107
  • Thank you. I had a feeling it was something dumb like this and I've tried a few variations but none worked. – Umzea Dec 07 '15 at 04:56
-1

Pass i to the getJSON method as a variable. You have sent it as a string by mistakenly.

 for (var i=1;i<=numPages;i++)
 {          

    buttons.append($("<button onclick='getJSON("+i+")'>"+i+"</button>"));

 }