开发者

Select all the <tr> tags less than the index of the focused <tr> tag

I am trying to access the <tr> tags of the 开发者_开发知识库focused <tr> tag, but it is displaying all of them. Can anyone solve this?

Below is my HTML and javascript code:

<table>
   <tr><td><input type="text"></td></tr>
   <tr><td><input type="text"></td></tr>
   <tr><td><input type="text"></td></tr>
   <tr><td><input type="text"></td></tr>
</table>

Below is the script i have written:

 $('TABLE TR TD').find('input').focus(function()
 {
   var ParID=$(this).parents('TR').index();
   $(this).parents('TR').siblings('TR').prevAll("TR").find('input').each(function()
     {
       alert($(this).parents('TR').index()) 
     });
 });


This should do it:

$('table input').focus(function() {
   var $previousRows = $(this).closest('tr').prevAll('tr');
});

Your problem is this part: .siblings('TR').prevAll("TR").

As .siblings('TR') returns all row (also the last one), .prevAll("TR") will return all rows too. Just removing .siblings('TR') would probably work fine too.

Note that .closest() [docs] is better suited in the situation.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜