I am attempting to assign an onclick attribute to each button generated through a for loop, without success. The loop generates a table that is populated with search results and the button has to pass a value to JPlayer. The following code, using the class of the button + i plain doesn't work, although I'm not sure why. Removing the i variable will obviously just assign the event handler to the last element in the array, which indeed it does. I've looked through a few similar questions here, as I gather this is a common pitfall with JS loops, but I can't make any of the answers work for this situation.
function displayResults(searchData){
var numResults = searchData.results.length;
$("#searchResults").html("");
var table = document.createElement("table");
table.setAttribute("class", "table");
for(var i = 0;i < numResults; i++) {
var resultTr = document.createElement("tr");
var results = searchData.results[i];
var resultArtist = document.createElement("td");
resultArtist.appendChild(document.createTextNode(results.artist));
var resultSong = document.createElement("td");
resultSong.appendChild(document.createTextNode(results.songTitle));
var resultAlbum = document.createElement("td");
resultAlbum.appendChild(document.createTextNode(results.album));
var resultDisk = document.createElement("button");
resultDisk.setAttribute("class", "playButton" +i);
$( ".playButton" +i).on( "click", { value: results.diskLocation }, function( event ) {
player(event.data.value);
});
resultDisk.appendChild(document.createTextNode("play"));
resultTr.appendChild(resultArtist);
resultTr.appendChild(resultSong);
resultTr.appendChild(resultAlbum);
resultTr.appendChild(resultDisk);
table.appendChild(resultTr);
$("#searchResults").append(table);
}
}
I've tried using this
, but I cannot seem to make that work either. So, how does one correctly assign event handlers to dynamically-produced elements in a loop?