【问题标题】:Running jQuery function on dynamically created content在动态创建的内容上运行 jQuery 函数
【发布时间】:2013-05-03 15:42:56
【问题描述】:

我有一个脚本,当用户单击页面上的某些 div 链接时,它会动态地将行添加到表中。我现在正在尝试添加一个删除按钮,以便用户可以删除他们不想要的添加行,但我在让它们工作时遇到了问题。

我用来删除表格行的代码来自here。我的代码是:

$('.addRow').click(function() {
      var tr = $(
      '<tr><td class="cat"></td>' 
      + '<td class="sel"></td>'
      + '<td><textarea name="paragraph[' + count + ']">Click to edit (id ' + count + ')</textarea><input type="hidden" name="catText[' + count + ']" class="hiddenCat"><input type="hidden" name="selText[' + count + ']" class="hiddenSel">'
      + '</td><td><button type="button" class="removebutton">Remove row</button></td></tr>');
      $('.mainTable > tbody:last').one().append(tr);
      tr.find(".cat").text($(this).closest("li.category").attr("title"));
      tr.find(".hiddenCat").val($(this).closest("li.category").attr("title"));
      tr.find(".sel").text($(this).closest("li.select").attr("title"));
      tr.find(".hiddenSel").val($(this).closest("li.select").attr("title"));
      count++;
    });

     $('.removebutton').click(function() {
      alert('Hello');
      var whichtr = $(this).closest("tr");       
      whichtr.remove();      
    });

addRow 函数将表行附加到选定的表。在其中一个单元格中有一个带有“removebutton”类的按钮。单击此按钮时,它应该删除该行。出于测试目的,使用警报消息;但是,当我单击使用 addRow 动态生成的按钮之一时,没有任何反应。

当我使用“removebutton”类静态添加按钮或链接时,会显示警报消息。

为什么在通过 jQuery 创建按钮时会出现问题,导致其无法正常工作?

【问题讨论】:

标签: jquery


【解决方案1】:

.on 用于动态内容:

$(document).on('click', '.removebutton', function() {
  alert('Hello');
  var whichtr = $(this).closest("tr");       
  whichtr.remove();      
});

【讨论】:

  • 像魅力一样工作,非常感谢!当 SO 允许我时,将接受为正确答案。
【解决方案2】:

动态创建的元素需要事件委托

$('.mainTable').on('click','.removebutton',function() {
  alert('Hello');
  var whichtr = $(this).closest("tr");       
  whichtr.remove();  
});

http://api.jquery.com/on/

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-03-15
    • 2012-07-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多