Jump to content

jQuery Plug-in return values


davej

Recommended Posts

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

  • 3 weeks later...

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

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 account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...