I am using jQuery.ajax to read and render XML file into HTML.
The below code generates a table of buttons for each data record in the XML:
$(xml).children('run').each(function() {
var runname = $(this).children('name').text();
buttonHtml = '<tr><td class="expbutton" id="runExpButton" onmousedown="myFunc(runname)">Click me</td></tr>';
$('#Runs').append(buttonHtml);
});
It’s not hard to see what I want to achieve here. But obviously it does not work.
My question is how do I achieve this in jQuery? If I use .live or .on methods I don’t have access to the local variable such as “runname”.
[EDIT]
Attempt on using jQuery.data():
$(xml).children('run').each(function() {
var runname = $(this).children('name').text();
buttonHtml = '<tr><td class="expbutton" id="runExpButton" onmousedown="myFunc(runname)">Click me</td></tr>';
$('#runExpButton').data('runname', runname);
$('#Runs').append(buttonHtml);
});
$('#runExpButton').live('click',function() {
alert($(this).data("runname"));
});
It does not seem to work? Only one of the buttons has the correct data value.
Because all the buttons have the same id, I suspect .data() doesn’t work with this?
What I believe you are looking for is jQuery .data()
You can store data for an html element and then pull that data in when the element is clicked.
An example would be
I edited your code to add unique IDs to each cell you are adding to the table.