javascript 如何判断您当前是否在 HTML 表格的最后一行?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4444575/
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-10-25 11:27:59  来源:igfitidea点击:

How to tell if you're currently in the last row of an HTML table?

javascriptjqueryhtmlhtml-table

提问by ghost_mv

I have a keydown event that I'm using to add a blank row to a table. But I only want the new row to be added if the keydown event happens when the cursor is in last row of the table.

我有一个 keydown 事件,我用它向表中添加一个空白行。但是我只希望在光标位于表的最后一行时发生 keydown 事件时添加新行。

This is my current jQuery event. .glCreditValue is the class of an input textbox that resides in the last TD of the table row. So when the user tabs out of that input, IF the TD that the input is inside of is in the last row of the table, I want to add a new row.

这是我当前的 jQuery 事件。.glCreditValue 是位于表行的最后一个 TD 中的输入文本框的类。因此,当用户退出该输入时,如果输入所在的 TD 位于表的最后一行,我想添加一个新行。

Being that the table data is generated dynamically, every row's final TD has an input textbox with the class .glCreditValue.

由于表数据是动态生成的,每一行的最终 TD 都有一个输入文本框,类为 .glCreditValue。

$(".glCreditValue").keydown(function(event) {
        var keycode = event.keyCode;
        if (keycode == 9) {
            //HERE i would like to make sure that i'm in the last row of the table
            AddNewRow();
        }
    });

I'm trying to make use of the tr:last selector, but I'm not sure quite where to go from here.

我正在尝试使用 tr:last 选择器,但我不确定从这里开始。

回答by Nick Craver

There are a few ways to do this, for example you could check the .closest()parent <tr>and see if it .is()a :last-child, like this:

有几种方法可以做到这一点,例如,您可以检查.closest()父级<tr>并查看它是否为.is()a :last-child,如下所示:

$(".glCreditValue").keydown(function(event) {
  if (event.which == 9 && $(this).closest("tr").is(":last-child")) {
      AddNewRow();
  }
});

回答by user113716

One way to do it without having the overhead of running a selector is to simply get the .closest()row, then go to the .next()elementand test its .lengthproperty.

做到这一点,而无需运行选择的开销的一种方法是简单地拿到.closest()一排,然后去.next()元素,并测试.length性能

It will be 0if you were on the last <tr>.

这将是0,如果你是在最后<tr>

if( !$(this).closest('tr').next().length ) {
   // was the last row
}