I am iterating over elements in a container and adding onClick to every element. I wish to execute a method which accepts an id as parameter when I click on an element. The id is unique to each element.
Below is my code:
$(document).ready(function()
{
var conElement = document.getElementById("my-container");
if (conElement)
{
var bookElements = conElement.getElementsByClassName("book-elements");
for (var element = bookElements.length; element--; )
{
var bookElement = bookElements[element];
var bookId = bookElement.getAttribute('book-id');
alert ('Book id is ' + bookId);
bookElement.onclick = function() {showBookSummary(bookId)};
}
}
});
function showBookSummary(bookId)
{
alert ('Book id inside showBookSummary is ' + bookId);
}
Issue: Same book id is passed everytime I click on any element. Suppose I have 3 elements and id for 1st element is "123", 2nd element is "456" and 3rd element is "789". Whenever I click on any of the 3 elements, it always passes id "123" as bookId to showBookSummary function.
Am I missing anything in here?