相同类名但不是同级别的最后一个元素_jQuery查找特定类的下一个/上一个元素,但不一定是同级...

bd96500e110b49cbb3cd949968f18be7.png

The next, prev, nextAll and prevAll methods are very useful, but not if the elements you are trying to find are not in the same parent element. What I want to do is something like this:

Hello

World>

When the span with the id click is pressed, I want to match the next element with the class find, which in this case is not a sibling of the clicked element so next() or nextAll() won't work.

解决方案

I was working on this problem myself today, here's what I came up with:

/**

* Find the next element matching a certain selector. Differs from next() in

* that it searches outside the current element's parent.

*

* @param selector The selector to search for

* @param steps (optional) The number of steps to search, the default is 1

* @param scope (optional) The scope to search in, the default is document wide

*/

$.fn.findNext = function(selector, steps, scope)

{

// Steps given? Then parse to int

if (steps)

{

steps = Math.floor(steps);

}

else if (steps === 0)

{

// Stupid case :)

return this;

}

else

{

// Else, try the easy way

var next = this.next(selector);

if (next.length)

return next;

// Easy way failed, try the hard way :)

steps = 1;

}

// Set scope to document or user-defined

scope = (scope) ? $(scope) : $(document);

// Find kids that match selector: used as exclusion filter

var kids = this.find(selector);

// Find in parent(s)

hay = $(this);

while(hay[0] != scope[0])

{

// Move up one level

hay = hay.parent();

// Select all kids of parent

// - excluding kids of current element (next != inside),

// - add current element (will be added in document order)

var rs = hay.find(selector).not(kids).add($(this));

// Move the desired number of steps

var id = rs.index(this) + steps;

// Result found? then return

if (id > -1 && id < rs.length)

return $(rs[id]);

}

// Return empty result

return $([]);

}

So in your example

hello

world>

you could now find and manipulate the 'p' element using

$('#click').findNext('.find').html('testing 123');

I doubt it will perform well on large structures, but here it is :)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值