简体   繁体   English

从表格点击事件获取HTML表格的行索引-JQuery

[英]Getting the Row index of a HTML table from table click event - JQuery

Can someone please help me crack this. 有人可以帮我解决这个问题。 I have a HTML table with an event when clicked to show a dialog. 单击显示对话框时,我有一个带有事件的HTML表。 I also want to get the row index of the clicked row, but it only outputs something different. 我也想获得被点击的行的行索引,但是它只输出不同的东西。

//script for the table event
 <script>
    $(function() {
       $( "#table").click(function(){

           $( "#dialog-modal1" ).dialog({
              height: 140,
              modal: true,
              title:"Search Item",
              width : 440,
              position: {my: "top", at: "bottom", of: "#table"}
            });
           $( "#dialog-modal1" ).show();

           var row = $('<tr></tr>').text($(this).index());
           alert(row);

        });
     });
</script>

The dialog shows as expected when the table is clicked but the output for row index is not what I want. 单击该表时,对话框将按预期显示,但行索引的输出不是我想要的。 It always outputs [object Object] . 它总是输出[object Object] If the first row of the table was clicked, I expect the output to be 0 , second row should be 1 and so on. 如果单击表的第一行,我希望输出为0 ,第二行应为1 ,依此类推。 What am I doing wrong? 我究竟做错了什么?

One problem is you're binding a click event to the whole table. 一个问题是您要将click事件绑定到整个表。

$( "#table").click(function() { ...

Try 尝试

$("#table tr").click(function () { ...

Which means you're binding the event to each row in the table. 这意味着您要将事件绑定到表中的每一行。 Now inside the callback this will represent the row that was clicked. 现在回调里面this将代表被点击的行。

You also don't need to use alert (as suggested by @cl3m) or even create a tr to output the index. 您也不需要使用警报(如@ cl3m所建议),甚至无需创建tr即可输出索引。 You should be able to simply call: 您应该能够简单地致电:

console.log($(this).index());

and see the result in your browser's debugger. 并在浏览器的调试器中查看结果。

Here's a working fiddle: 这是一个工作的小提琴:

https://jsfiddle.net/860b9t73/ https://jsfiddle.net/860b9t73/

Check out the JsFiddle demo 查看JsFiddle演示

HTML 的HTML

<table>
  <tr>
    <td>FIRST</td>
  </tr>
  <tr>
    <td>SECOND</td>
  </tr>
  <tr>
    <td>THIRD</td>
  </tr>
</table>
<div id="result"></div>

JS JS

$('tr').click(function(){
  var $tr = $(this);
  $('#result').html("index clicked: " + $tr.index());
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM