Javascript 如何判断在表中单击了哪个行号?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4524661/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 12:46:58  来源:igfitidea点击:

How to tell which row number is clicked in a table?

javascriptjqueryhtmlhtml-tabledom-events

提问by Muhammad Zeeshan

I have a table like the following:

我有一张如下表:

<table>
   <tr>
      <td>1</td><td>1</td><td>1</td>
   </tr>
   <tr>
      <td>2</td><td>2</td><td>2</td>
   </tr>
   <tr>
      <td>3</td><td>3</td><td>3</td>
   </tr>
</table>

When a user clicks on the table, how can I get the index of this row (trelement)?

当用户单击表格时,如何获取该行(tr元素)的索引?

For example, when I click on the first tr(with 1s in the above table), it should pick it up and return 1.

例如,当我单击第一个tr1在上表中为s)时,它应该将其捡起并返回1

回答by Ken Redler

This would get you the index of the clicked row, starting with one:

这将使您获得单击行的索引,从一开始:

$('#thetable').find('tr').click( function(){
alert('You clicked row '+ ($(this).index()+1) );
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="thetable">
   <tr>
      <td>1</td><td>1</td><td>1</td>
   </tr>
   <tr>
      <td>2</td><td>2</td><td>2</td>
   </tr>
   <tr>
      <td>3</td><td>3</td><td>3</td>
   </tr>
</table>

If you want to return the number stored in that first cell of each row:

如果要返回存储在每行第一个单元格中的数字:

$('#thetable').find('tr').click( function(){
  var row = $(this).find('td:first').text();
  alert('You clicked ' + row);
});

回答by MasterAM

A better approach would be to delegate the event, which means catching it as it bubbles to the parent node.

更好的方法是委托事件,这意味着在它冒泡到父节点时捕获它。

delegation - overview

委托 - 概述

This solution is both more robust and efficient.

该解决方案更加稳健和高效。

It allows the event to be handled even if more rows are dynamically added to the table later, and also results in attaching a single event handler to the parent node (tableelement), instead of one for each child node (trelement).

即使稍后将更多行动态添加到表中,它也允许处理事件,并且还会导致将单个事件处理程序附加到父节点(table元素),而不是为每个子节点(tr元素)附加一个事件处理程序。

Assuming that the OP's example is a simplified one, the table's structure can be more complex, for example:

假设 OP 的例子是一个简化的例子,表的结构可以更复杂,例如:

<table id="indexedTable">
    ...
    <tr>
        <td><p>1</p></td>
        <td>2</td>
        <td><p>3</p></td>
    </tr>
</table>

Therefore, a simplistic approach such as getting e.target.parentElementwill not work, as clicking the internal <p>and clicking the center <td>will produce different results.

因此,像获取这样的简单方法是e.target.parentElement行不通的,因为单击内部<p>和单击中心<td>会产生不同的结果。

Using delegation normalizes the event handling, only assuming that there are no nested tables.

使用委托规范了事件处理,仅假设没有嵌套表。

implementation

执行

Both of the following snippets are equivalent:

以下两个片段是等效的:

$("#indexedTable").delegate("tr", "click", function(e) {
    console.log($(e.currentTarget).index() + 1);
});

$("#indexedTable").on("click", "tr", function(e) {
    console.log($(e.currentTarget).index() + 1);
});

They attach a listener to tableelement and handle any event that bubbles from the table rows. The current API is the onmethod and the delegatemethod is legacy API (and actually calls onbehind the scenes).

他们将侦听器附加到table元素并处理从表行中冒泡的任何事件。当前 API 是on方法,delegate方法是遗留 API(实际上on是在幕后调用)。

Note that the order of parameters to both functions is different.

请注意,两个函数的参数顺序不同。

example

例子

A comparison between direct handler attachment and delegation is available below or on jsFiddle:

下面或在 jsFiddle 上提供了直接处理程序附件和委托之间的比较:

$("#table-delegate").on("click", "tr", function(e) {
  var idx = $(e.currentTarget).index() + 1;
  $("#delegation-idx").text(idx);  
  console.log('delegated', idx);
});

$("#table-direct tr").on("click", function(e) {
  var idx = $(e.currentTarget).index() + 1;
  $("#direct-idx").text(idx);
  console.log('direct', idx);
});

$('[data-action=add-row]').click(function(e) {
  var id = e.target.dataset.table;
  $('#' + id + ' tbody')
    .append($('<tr><td>extra</td><td>extra</td><td>extra</td></tr>')[0])
});
tr:hover{
    background:#ddd;
}

button.add-row {
    margin-bottom: 5px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet"/>


<h1>Event handling test</h1>
<p>Add rows to both tables and see the difference in handling.</p>
<p>Event delegation attaches a single event listener and events related to newly added children are caught.</p>
<p>Direct event handling attaches an event handler to each child, where children added after the inital handler attachment don't have a handler attached to them, and therefore their indices won't be logged to console.</p>
<h2>Delegation</h2>
<p><span>row index: </span><span id="delegation-idx">unknown</span></p>
<button class="add-row" data-action="add-row" data-table="table-delegate">Add row to delegation</button>
<table id="table-delegate" class="table">
    <tbody>
    <tr>
        <td>normal</td>
        <td>normal</td>
        <td>normal</td>
    </tr>
    <tr>
        <td><p>nested</p></td>
        <td><p>nested</p></td>
        <td><p>nested</p></td>
    </tr>
    <tr>
        <td>normal</td>
        <td>normal</td>
        <td><p>nested</p></td>
    </tr>

</table>

<h2>Direct attachment</h2>
<p><span>row index: </span><span id="direct-idx">unknown</span></p>
<button class="add-row" data-action="add-row" data-table="table-direct">Add row to direct</button>
<table id="table-direct" class="table">
<tbody>
    <tr>
        <td>normal</td>
        <td>normal</td>
        <td>normal</td>
    </tr>
    <tr>
        <td><p>nested</p></td>
        <td><p>nested</p></td>
        <td><p>nested</p></td>
    </tr>
    <tr>
        <td>normal</td>
        <td>normal</td>
        <td><p>nested</p></td>
    </tr>
    
</tbody>
</table>

Here's the demo on jsFiddle.

这是jsFiddle上的演示

P.S:

PS:

If you do have nested tables (or, in the general case, wish to delegate to elements with specific depth), you can use this suggestion from the jQuery bug report.

如果您确实有嵌套表(或者,在一般情况下,希望委托给具有特定深度的元素),您可以使用jQuery 错误报告中的建议

回答by rahul

You can use object.rowIndexproperty which has an index starting at 0.

您可以使用object.rowIndex索引从 0 开始的属性。

$("table tr").click(function(){
    alert (this.rowIndex);
});

See a working demo

查看工作演示

回答by amd

A simple and jQuery free solution:

一个简单且免费的 jQuery 解决方案:

document.querySelector('#elitable').onclick = function(ev) {
   // ev.target <== td element
   // ev.target.parentElement <== tr
   var index = ev.target.parentElement.rowIndex;
}

Bonus:It works even if rows are added/removed dynamically

奖励:即使动态添加/删除行,它也能工作

回答by miqbal

$('tr').click(function(){
 alert( $('tr').index(this) );
});

For first tr, it alerts 0. If you want to alert 1, you can add 1 to index.

首先tr,它提醒 0。如果你想提醒 1,你可以将 1 添加到索引。

回答by Ludus H

In some cases we could have a couple of tables, and then we need to detect click just for particular table. My solution is this:

在某些情况下,我们可能有几个表,然后我们需要检测特定表的点击。我的解决方案是这样的:

<table id="elitable" border="1" cellspacing="0" width="100%">
  <tr>
 <td>100</td><td>AAA</td><td>aaa</td>
  </tr>
  <tr>
<td>200</td><td>BBB</td><td>bbb</td>
   </tr>
   <tr>
<td>300</td><td>CCC</td><td>ccc</td>
  </tr>
</table>


    <script>
    $(function(){
        $("#elitable tr").click(function(){
        alert (this.rowIndex);
        });
    });
    </script>

DEMO

演示