在我的网络应用程序中,我使用 jQuery 动态创建实时提要以解析 JSON 对象,并在 html 中动态创建表格行(有关示例,请参阅我之前的问题 here)
我从 JSON 对象动态创建的每个表行,我添加一个图像(使用标准的 html img 标签) - 我现在想做的是创建一个 .click() 函数,当它出现时执行异步 ajax 调用图像被点击。
所以,如果我动态创建表格行的代码如下所示:
var html = "<tr>"
+ "<td><img class=\"status_refresh\" src=\"/refresh.png\" id=\"refresh_id\"/></td>"
+ "</tr>";
$('#peopleDirectory').append(html);
在我的 JSP 中,定义了 peopleDirectory div,并将附加 html,我有以下 javascript:
$('.status_refresh').click(function () {
console.log($(this).attr('id'));
});
但是当我点击时什么也没有发生..任何人都可以告诉我做错了什么吗?
谢谢!
最佳答案
click
事件仅绑定(bind)到绑定(bind)时存在的对象。要将事件绑定(bind)到所有现有的 和 future 的 对象,请使用 live
方法。 Source Link
Description: Attach a handler to the event for all elements which match the current selector, now and in the future.
$('.status_refresh').live('click', function () {
console.log($(this).attr('id'));
});
关于javascript - 添加 jQuery .click() 到动态创建的 HTML,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5783045/