How to find whether Current TD is last TD in TR

﹥>﹥吖頭↗ 提交于 2020-01-03 21:04:33

问题


I have a single row and multiple <td>s in it. In one of my functions I come across a situation where I have to find out whether my currentSelectedTD is the last <td> in the row so that I can treat it diffrently.

I tried $(currentSelectedTD).is(":last") which is not working and always returns true. I have also tried couple of other possibilities which are not working.

Thanks in advance.


回答1:


You can use .next() to check if the element has the immediately following sibling.

if( $(currentSelectedTD).next().length == 0) {
    // is last 
}



回答2:


Think you should do :last filter on the full set and store the result in a variable. Then do a loop through the set and compare each one with the one you stored.




回答3:


use-

if($('.currentSelectedTD:last')){
//do what ever you want
}

or

$lastTd = $('.currentSelectedTD').parent('tr').find('td:last')



回答4:


You can check for this quite easily, and without tapping into jQuery:

var isLastChild = currentSelectedTD.parentNode.lastElementChild == currentSelectedTD;

This has the advantage of being both native DOM and simple, however it would only work on a modern browser (e.g. needs IE9). You can tweak it to work with anything, but then it wouldn't be an one-liner.




回答5:


You just need to use:

$(currentSelectedTD).is("td:last");


来源:https://stackoverflow.com/questions/6705399/how-to-find-whether-current-td-is-last-td-in-tr

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!