davej Posted March 30, 2016 Share Posted March 30, 2016 I have been looking at the examples here... https://learn.jquery.com/plugins/basic-plugin-creation/ ...but I am confused about the return values. Some examples seem to return collections such as... $.fn.myNewPlugin = function() { return this.each(function() { // Do something to each element here. }); }; ...but some seem to work on collection but (apparently) return only one item... (function( $ ) { $.fn.showLinkLocation = function() { this.filter( "a" ).each(function() { var link = $( this ); link.append( " (" + link.attr( "href" ) + ")" ); }); return this; }; }( jQuery )); ...or am I reading this wrong? Link to comment Share on other sites More sharing options...
justsomeguy Posted March 30, 2016 Share Posted March 30, 2016 I may be wrong, but I believe that this.each returns this, so that's what gets returned in the first example. Link to comment Share on other sites More sharing options...
davej Posted March 30, 2016 Author Share Posted March 30, 2016 Now I am thinking that they both return collections, but I don't understand how they differ. Link to comment Share on other sites More sharing options...
justsomeguy Posted March 30, 2016 Share Posted March 30, 2016 To support method chaining I think they would always return the same object where they're defined. Namely, this. Link to comment Share on other sites More sharing options...
davej Posted April 15, 2016 Author Share Posted April 15, 2016 Here is a somewhat related question... If I have a jQuery plugin defined like this... (function($) { $.fn.processImages = function() { return this.filter('img').each(function() { // process all the img elements inside the div }); // end each }; }( jQuery )); ...and I launch it like this... $(document).ready(function() { $("#myDiv").processImages(); // pass it the div which contains the images }); ...how do I change the plugin so that it will extract a list of images from within the selected div or divs? The filter function is not sufficient to accomplish this refined-selection. What I need is something like... $(this "img").each(function(){... ---EDIT--- I found the solution. An optional context can be used in a selector so that you don't begin searching at the document root. This is just what I needed in the event handler... $("img", this).each(function(){... Link to comment Share on other sites More sharing options...
Recommended Posts
Create an account or sign in to comment
You need to be a member in order to leave a comment
Create an account
Sign up for a new account in our community. It's easy!
Register a new accountSign in
Already have an account? Sign in here.
Sign In Now