onmousedown在动态生成的html元素上 [英] onmousedown on dynamically generated html elements
问题描述
我正在使用jQuery.ajax来读取XML文件并将其呈现为HTML.
I am using jQuery.ajax to read and render XML file into HTML.
下面的代码为XML中的每个数据记录生成一个按钮表:
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.
我的问题是如何在jQuery中实现这一目标?如果我使用.live或.on方法,则无法访问本地变量(例如"runname").
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".
尝试使用jQuery.data():
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.
因为所有按钮都具有相同的ID,我怀疑.data()不能与此一起使用?
Because all the buttons have the same id, I suspect .data() doesn't work with this?
推荐答案
我相信您正在寻找的是jQuery .data()
What I believe you are looking for is jQuery .data()
您可以存储html元素的数据,然后在单击该元素时将其拉入.
You can store data for an html element and then pull that data in when the element is clicked.
一个例子是
$(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'));
});
我编辑了您的代码,以向要添加到表中的每个单元格添加唯一的ID.
I edited your code to add unique IDs to each cell you are adding to the table.
这篇关于onmousedown在动态生成的html元素上的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!