问题
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?
回答1:
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
$(xml).children('run').each(function(index) {
var runname = $(this).children('name').text();
buttonHtml = '<tr><td class="expbutton" id="runExpButton'+index+'">Click me</td></tr>';
$('#Runs').append(buttonHtml);
$('#runExpButton'+index).data('runname', runname);
});
$(document).on('click', '.expbutton', function(){
alert($(this).data('runname'));
});
I edited your code to add unique IDs to each cell you are adding to the table.
回答2:
You can change you HTML to something like
buttonHtml = '<tr><td class="expbutton" id="runExpButton" data-name="' + runname + '">Click me</td></tr>';
and then, as Blake stated correctly, use $(element).data('name') to get that value. So bind the event with .live, read data-name, profit!
来源:https://stackoverflow.com/questions/13984136/onmousedown-on-dynamically-generated-html-elements