开发者

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

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.

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.

Being that the table data is generated dynamically, every row's final TD has an input textbox with the class .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.


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:

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


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() element and test its .length property.

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

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜