开发者

Using next() x number of times with jQuery

What's an easy way to iterate x number of times using next() (applying the same function each time)?

I am working in Sharepoint and have limited control of the HTML; what I can do is find an element by its ID, track down the closest <td>, hide() it, and then move on to the next one (I don't want all the <td>'s, just about 7 or 8 in a row).

The code below works but it's not that pretty.

$("#my-easily-identifiable-id").closest("td").hide();
$("#my-easily-identifiable-id").closest("td").next().hide();
$("#my-easily-identifiable-id").closest("td").next().next().hide();
$("#my-easily-identifiable-id").closest("td").next().next().next().hide();
[ ... etc ... ]

What's a better way to do this?

Than开发者_JAVA技巧ks

PS: added a fiddle (genius)


Use .nextAll() + .andSelf() with .slice().

$("#my-easily-identifiable-id").closest("td").nextAll().andSelf().slice(0, 7);


I think a simpler solution than those posted so far would be .nextUntil():

//to get next 8 elements
var i = $('#my-easily-identifiable-id').index();
$('#my-easily-identifiable-id').closest('td').nextUntil('', ':lt(' + (i+8) + ')');

//to get self and next 3
var i = $('#my-easily-identifiable-id').index();
$('#my-easily-identifiable-id').closest('td').nextUntil('', ':lt(' + (i+3) + ')').andSelf();

Grabs all "next" elements until the filter is hit (in this case we choose the next 8 elements). Verified by jsFiddle.


I've not tried it, but perhaps the following might work (I'll test momentarily):

$("#my-easily-identifiable-id").siblings().slice($(this).index(),($(this).index() + 8)).hide();

Tested and verified with a JS Fiddle demo.


Maybe something like this:

$("#my-easily-identifiable-id").closest("td").hide();
$("#my-easily-identifiable-id").closest("td").nextAll().hide();
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜