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

时间:2016-11-11 13:39:51

标签: javascript jquery

背景资料

我有一个包含大量数据行的表。每行中都包含一个按钮,用户可以删除当前行。 我不知道我最终会得到多少行数据。因此需要一个通用的按钮处理程序......除非有另一种更好的方法。

我的表格如下:

<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)

任何建议都将不胜感激。

1 个答案:

答案 0 :(得分:0)

您必须按照课程来处理动态点击,因为您无法使用ID处理动态点击。

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