从 table 单击事件获取 HTML table 的行索引 - JQuery

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

有人可以帮我破解吗?单击以显示对话框时,我有一个 HTML table 事件。我也想获取点击行的行索引,但它只输出不同的东西。

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

单击 table 时对话框按预期显示,但行索引的输出不是我想要的。它总是输出[object Object]。如果单击 table 的第一行,我希望输出为 0,第二行应为 1等等。我做错了什么?

一个问题是您将点击事件绑定到整个 table。

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

尝试

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

这意味着您将事件绑定到 table 中的每一行。现在在回调中 this 将代表被点击的行。

您也不需要使用警报(如@cl3m 所建议的那样),甚至不需要创建 tr 来输出索引。您应该可以简单地调用:

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

并在浏览器的调试器中查看结果。

这是一个工作 fiddle:

https://jsfiddle.net/860b9t73/

查看 JsFiddle demo

HTML

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

JS

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