首页 > 解决方案 > 如何使用 jQuery 添加按钮?

问题描述

我使用 ajax 在我的页面上呈现表格。在表格的最后一行中,我试图显示一个正在处理我的“编辑”功能的按钮,如下所示:

$(".editPersonnel").on("click", function () {
$("#editPersonnelModal").modal("show");
$tr = $(this).closest("tr");

var data = $tr
  .children("td")
  .map(function () {
    return $(this).text();
  })
  .get();

$("#idPer").val(data[0]);
$("#updateLastName").val(data[1]);
$("#updateFirstName").val(data[2]);
$("#updateJobTitle").val(data[3]);
$("#updateEmail").val(data[4]);
$("#updateDepartment").val(data[5]);
$("#updateLocation").val(data[6]);
console.log(data);

});

我尝试使用 jQuery 呈现该按钮,但是当我这样做时:

 $("<td>").html(
             '<td><button class="btn btn-info editPersonnel">Edit</button>'
            )

该按钮显示在页面上,但不起作用。谁能帮我解决这个问题?我还是个新手……谢谢!

标签: javascripthtmljqueryajaxbutton

解决方案


您可以使用事件委托,因为元素是动态创建的。

// Replace document with nearest static parent/ancestor, if possible
$(document).on("click", ".editPersonnel", function (){
   // ...
});

推荐阅读