如何为动态生成id的按钮编写事件处理程序

how to write an event handler for a button whose id is generated dynamically?

本文关键字:按钮 事件处理 程序 id 动态      更新时间:2023-09-26

背景信息

我有一个表与一堆行的数据。每行中包含一个按钮,该按钮应允许用户删除当前行。我事先不知道最终会有多少行数据。因此需要一个通用的按钮处理程序…除非有更好的办法。

我的表是这样的:

<table class="table table-bordered table-hover tcdata">
  <tbody>
    <tr>
      <td colspan="6">
        <h3>Time Conditions</h3></td>
    </tr>
    <tr id="tcrow0">
      <td>
        <button id="del_tc0" type="button" class="btn btn-warning btn-circle deletename"><i class="fa fa-times"></i></button>&nbsp;&nbsp;TC 1:</td>
      <td>
        <input class="form-control starttc tcdata" type="input" placeholder="UTC Start Time (format 00:00:00)" name="starttime0" id="starttime0" value="00:00:00">
      </td>
      <td>
        <input class="form-control starttc tcdata" type="input" placeholder="UTC End Time (format 00:00:00)" name="endtime0" id="endtime0" value="00:00:00">
      </td>
      <td>
        <input class="form-control starttc tcdata" type="input" placeholder="Extension" name="extension0" id="endtime0" value="101">
      </td>
      <td>
        <input class="form-control starttc tcdata" type="input" placeholder="Domain" name="domain0" id="endtime0" value="testdomain">
      </td>
      <td>
        <input class="dow" id="hidden_dow0" type="hidden" value="m,t,w,r,f,s,n">
        <label class="checkbox-inline"><b>Days of Week:</b></label>
        <input class="checkbox-inline tcdata" type="checkbox" id="dow_m0" name="dow_m0">Mon&nbsp;
        <input class="checkbox-inline tcdata" type="checkbox" id="dow_t0" name="dow_t0">Tue&nbsp;
        <input class="checkbox-inline tcdata" type="checkbox" id="dow_w0" name="dow_w0">Wed&nbsp;
        <input class="checkbox-inline tcdata" type="checkbox" id="dow_r0" name="dow_r0">Thu&nbsp;
        <input class="checkbox-inline tcdata" type="checkbox" id="dow_f0" name="dow_f0">Fri&nbsp;
        <input class="checkbox-inline tcdata" type="checkbox" id="dow_s0" name="dow_s0">Sat&nbsp;
        <input class="checkbox-inline tcdata" type="checkbox" id="dow_n0" name="dow_n0">Sun&nbsp;</td>
    </tr>
    <tr>
      <td>
        <button id="addtc" type="button" class="btn btn-success btn-circle"><i class="fa fa-plus"></i></button>
      </td>
    </tr>
    <tr id="submitbtnsection">
      <td colspan="6" align="center">
        <input type="submit" name="submit" id="submit" class="btn btn-primary" value="Save">&nbsp;&nbsp;
        <input type="button" name="cancel" id="cancel" class="btn btn-warning submit" value="Cancel">&nbsp;&nbsp;
        <input type="button" name="unassign" id="unassign" class="btn btn-warning" value="Unassign">
      </td>
    </tr>
  </tbody>
</table>

我需要一种方法来编写一个jquery函数,将捕获任何时候一个"del_tcX"按钮被点击,然后删除表行有相应的X值。(tcrowX)

你必须使用class来处理动态点击,因为你不能使用ID来处理动态点击。

$(document).on('click', '.del_tcX', function() {
    // do something
    //To remove current row 
    $(this).closest('tr').remove()
});