简体   繁体   English

如何编写jQuery遍历函数

[英]How to write jQuery traversal function

I want to write a jQuery function called nextOrPrev() that works similar to jQuery's next() and prev() , which returns the next sibling or, in case there isn't any, the previous one. 我想编写一个名为nextOrPrev()的jQuery函数,其功能类似于jQuery的next()prev() ,该函数返回下一个同级项,或者如果没有,则返回前一个同级项。 The function should be compatible with jQuery's existing traversal functions like siblings() , but also end() . 该功能应与jQuery现有的遍历功能(如siblings()以及end()兼容。

What do I have to write in $.fn.extend() ? 我必须在$.fn.extend()写什么?

My attempt was to create an array and then populate it in a this.each loop and at the end, return it, but returning that creates a new stack. 我的尝试是创建一个数组,然后在this.each循环中填充它,最后返回它,但是返回创建一个新堆栈。

Shouldn't be a problem, just write it like any jQuery plugin 应该没问题,就像任何jQuery插件一样编写

$.fn.nextOrPrev = function() {
    var args = arguments;
    return $(this).map(function(_,el) {
        var next = $.fn.next.apply($(el), args);
        return (next.length ? next : $.fn.prev.apply($(el), args)).get();
    });
}

and use it 并使用它

$('#elem1, #elem2').nextOrPrev()

FIDDLE 小提琴

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM