Find Table Row Index using jQuery

前端 未结 4 1583
我在风中等你
我在风中等你 2021-01-04 04:21

I\'m an intermediate user in jQuery. I know to find the rowIndex of a table using jQUery, but my scenario is a different one. My table(GridView) consists of 20 columns and e

4条回答
  •  南方客
    南方客 (楼主)
    2021-01-04 05:00

    sectionRowIndex is a property of the element, not an attribute.

    The correct way to modify your sample code is to access the jQuery item with a zero indexer like this:

    $("#gv1 tr input[name $= 'txtName']").live('click', function(e){
       alert($(this).closest('td').parent()[0].sectionRowIndex);
    });
    

    This will return the correct row index for you. Also, if you are going to use jQuery's .closest() function to traverse up the DOM and also .parent(), why not compine those two and just traverse up to the closest element?

    $("#gv1 tr input[name $= 'txtName']").live('click', function(e){
       alert($(this).closest('tr')[0].sectionRowIndex);
    });
    

    This will also handle weird cases where the parent->child relationship isn't exactly what you expected. For example if you chained a $(this).parent().parent() and then decided to wrap your inner cell with another div or span, you might screw up the relationship. The .closest() is the easy way out to make sure it will always work.

    Of course my code samples are re-using your provided sample above. You may wish to test with a simpler selector first to prove it works, then refine your selectors.

提交回复
热议问题