How can I make my jQuery plugin respect end ()?

With most jQuery function calls that change the selection, you can return to the selection step with end . For instance:

 $('#myElement').parent().show().end().css('color', '#ff0000'); 

This shows the parent and then makes the original selection red.

However, when I define my own jQuery plugin that filters the selection, I do not get this function. For instance:

 $.fn.nextBarOne = function(selector) { var ret = this.next().next(); return (typeof selector === 'undefined') ? ret : ret.filter(selector); } 

If I now do $('#myElement').nextBarOne().show().end() , I will not return to the original selection. Obviously, this is because inside the function it calls next twice, and sometimes it calls filter .

How can I define a jQuery plugin to allow me to use end , as inline functions do?

+4
source share
1 answer

Set prevObject after going through with .next() to point to the original jQuery object.

 $.fn.nextBarOne = function(selector) { var self = this, ret = (typeof selector === 'undefined') ? this.next().next() : this.next().next().filter(selector); ret.prevObject = self; return ret; } 

EDIT:

Possibly cleaner with pushStack() . I also included a selector in the pushStack call.

 $.fn.nextBarOne = function(selector) { var ret = (typeof selector === 'undefined') ? this.next().next() : this.next().next().filter(selector); return this.pushStack(ret, "nextBarOne", selector || ""); } 

Example here

+3
source

Source: https://habr.com/ru/post/1338946/


All Articles