如何从表体单击事件捕获行id

How to capture row id from table body click event

本文关键字:id 事件 单击      更新时间:2023-09-26

如何从动态创建的行元素中获取id ?下面是我尝试过的代码,但它不会触发事件。

   <table id="tblRawMaterials" cellpadding="0" cellspacing="0">
    <thead>
        <tr>
            <th>
                A
            </th>
            <th>
                B
            </th>
            <th>
                C
            </th>
        </tr>
    </thead>
    <tbody> 
        <tr id="DCB4325E-951C-67E3-1E8F-7270D488A1EB"  >
        <td>G20002</td>
        <td>1,783</td>
        <td>2,000</td>           
        </tr>
    </tbody>
</table>
脚本

 $("#tblRawMaterials tbody").click( function(e) {
           // Here i need to capture row id of clicked cell.
  });

Thanks in advance

你需要等效的(旧的)sintax on,完全相同的概念:

$("#tblRawMaterials tbody").delegate('tr', 'click', function(e) {
  console.log($(this).attr('id'))
});

你需要使用事件委托,通过这种方式,事件被附加到父对象上,并在点击tr时触发。它不依赖于tr,所以它也可以用于动态添加的元素。

请检查

您也可以这样尝试closest

$(document).ready(function() {
  $("#tblRawMaterials tbody").click(function(e) {
    var $tr = $(e.target).closest('tr'),
      rowId = ($tr).attr("id"); // Here you can capture the row id of clicked cell.
    alert(rowId);
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<table id="tblRawMaterials" cellpadding="0" cellspacing="0">
  <thead>
    <tr>
      <th>
        A
      </th>
      <th>
        B
      </th>
      <th>
        C
      </th>
    </tr>
  </thead>
  <tbody>
    <tr id="DCB4325E-951C-67E3-1E8F-7270D488A1EB">
      <td>G20002</td>
      <td>1,783</td>
      <td>2,000</td>
    </tr>
  </tbody>
</table>

更新:

如果您确实需要delegate,那么您可以使用以下代码片段:

$(document).ready(function () {
    $(document).delegate("#tblRawMaterials tbody", "click", function (e) {
        var $tr = $(e.target).closest('tr'),
          rowId = ($tr).attr("id"); // Here you can capture the row id of clicked cell.
        alert(rowId);
    });
});

注意:这里我没有为tr元素绑定点击事件。

希望这对你有帮助!

您需要使用事件委托,以这种方式将事件附加到父tbody并在单击tr时触发。它不依赖于tr,所以它也可以用于动态添加的元素。

$("#tblRawMaterials tbody").on('tr','click',function(e) {
  var id = $(this).attr('id');
});

使用jQuery委托

Description:为现在或将来匹配选择器的所有元素附加一个处理程序到一个或多个事件根元素的特定集合。

$("#tblRawMaterials tbody").delegate('tr','click',function(e) {
      var id = $(this).attr('id');
});

try this

$(document).ready(function () {
        $('#tblRawMaterials tr').click(function () {
            alert($(this).attr('id'));
        });
});