对动态添加的html元素调用jQuery方法

call on dynamic added html elements a jQuery method

本文关键字:调用 jQuery 方法 元素 html 动态 添加      更新时间:2023-09-26

my在动态添加的html元素上调用JavaScript/jQuery 1.9.1方法时遇到了一些问题。

这是我的JS代码:

$(".download").live("click", function() {
    var buttonId = $(this).attr("id");
    alert(buttonId);
});

我的动态HTML代码:

  var html = "";
    for(var i = 0; i <daten.length; i++) {
       html += "<input id='" + daten[i].pfad + "' class='download' type='image' width='25px' height='25px' src='/download.png'/>";
    }
  $("#table").append(html);

我没有收到错误消息,但方法除了不调用之外,还有什么不正确的?

尝试使用on(),因为live()在jQuery:的较新版本中已被弃用并删除

$('#table').on('click', '.download', function() {
    alert(this.id);
});

FIDDLE

对我有用吗?

使用.on代替

$(document).on("click",".download",function() {
    var buttonId = $(this).attr("id");
    alert(buttonId);
});

这样使用:

  $(document).on("click",".download",function() {
   //put your code here
  });