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