【问题标题】:Getting the Row index of a HTML table from table click event - JQuery从表单击事件中获取 HTML 表的行索引 - JQuery
【发布时间】:2016-02-16 13:30:10
【问题描述】:

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

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

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

【问题讨论】:

  • 你应该使用console.log(row)而不是alert(row),并在控制台中观察结果。
  • @cl3m console.log(row) 输出 [tr] 。仍然不是我想要的。
  • 您的代码中有很多错误。 1. 在您的“点击”处理程序中,“this”实际上是table 元素,而不是tr。 2. row var 是 tr,而 tr 不能包含文本,只能包含 tdth... 3. 你会看到 [object Object],因为 row var很好……一个对象。您可能想提醒.index() 值... 4. 查看我的答案:-)

标签: javascript html jquery-ui jquery-events


【解决方案1】:

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

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

试试

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

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

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

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

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

这是一个有效的小提琴:

https://jsfiddle.net/860b9t73/

【讨论】:

  • 非常感谢@Sergio
【解决方案2】:

查看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());
});

【讨论】:

    猜你喜欢
    • 2015-04-18
    • 1970-01-01
    • 2010-10-02
    • 2020-11-13
    • 2011-11-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多