开发者

Find row index using jQuery

<div class="parent">
  <div class="formR开发者_JAVA技巧ow js-TextBox"><a></div>  <------ index 0
  <div class="formRow js-Image"><a></div> <------ index 1
  <div class="formRow js-TextBox"><a></div><------ index 2
  <div class="formRow js-ImageList"><------ index 3
  <div class="formRow js-Image"><a></div> <-- **This should return 3 but is returning 4 because I search index on the basis of formRow**
</div>

Code to find the formRow index

var parent = $(this).parents("div.formRow");
var rowIndex = parent.parent().find("div.formRow").index(parent);

Please refer to above code and advise how I can find the index of formRow for which I have clicked on anchor element a.

The problem is that the last form row contains another formRow, but I want the index of parent form row.


I'd remove ambiguity and provide the row number to the element at render time, i.e.

<div class="formRow js-TextBox" id="row<%= rownumber %>"><a></div>

Or as the ID to the anchor:

<div class="formRow js-TextBox"><a id="row<%= rownumber %>"></div>

There are a multitude of ways to approach this. I always find that if something seems to hard then I'm approaching it from the wrong direction (or just plain wrong).


Can you modify the above - I'd add another css class - primaryRow to the first three and use that instead of formRow in the jQuery expression

OK - The run this code:

 $('.parent > div').addClass('primaryRow');

to add the class.

Then

 var rowIndex = $('.primaryRow').index($(this).parents().find('.primaryRow'));


This works.

$('a').click(function(){
var i = $(this).parents('.parent > .formRow').index('.parent > .formRow');
alert(i);
    return false;
});

Check it out: jsfiddle

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜