接下来的prev,nextAll和prevAll方法是非常有用的,但如果您尝试查找的元素不在同一个父元素中,则不会。我想做的是这样的:
<div> <span id="click">Hello</span> </div> <div> <p class="find">World></p> </div>
当按住id点击的跨度时,我想将下一个元素与类find匹配,在这种情况下,它不是点击的元素的兄弟,所以next()
或nextAll()
将不起作用。
解决方法
我今天自己在处理这个问题,这是我想出来的:
/** * 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 $([]); }
所以在你的例子中
<div><span id="click">hello</span></div> <div><p class="find">world></p></div>
您现在可以使用“p”元素查找和操作
$('#click').findNext('.find').html('testing 123');
我怀疑它会在大型结构上表现很好,但这里是:)