Skip to content Skip to sidebar Skip to footer

Jquery Return Value

I used a code: jQuery.fn.MyFunction = function(){ return this.each(function() { attributes = 'test'; return attributes; });} But when I call var1 = $(this).MyFunctio

Solution 1:

jQuery plugins are generally designed to return a jQuery object so you can chain method calls:

jQuery("test").method1().method2() ...

If you want to return something else, use the following syntax:


jQuery.fn.extend({
    myFunction: function( args ) {
            attributes = "test";

            return attributes;
    }
});

, or access it via its index using [].

Solution 2:

Here is once again your code:

jQuery.fn.MyFunction = function() { #1return this.each(function() {    #2return"abc";                 #3
   });                              #4
};                                  #5

Now let's check what every line do.

  1. We declare property MyFunction which is a function for every jQuery object.
  2. This line is first and the last statement of jQuery.MyFunction(). We return the result of this.each(), not the result of lambda-function (used as a argument for jQuery.each()). And this.each() returns itself so the final result is that you get jQuery object returned.

Lines 3-5 are not important in fact.

Just consider those two examples:

jQuery.fn.MyFunction = function() {
    returnthis.each(function() {
        return"abc";
    });
};

jQuery.fn.AnotherFunction = function() {
    return"Hello World";
};

varMyFunctionResult = $(document).MyFunction();
varAnotherFunctionResult = $(document).AnotherFunction();

alert(MyFunctionResult);
alert(AnotherFunctionResult);

Solution 3:

I believe jQuery returns the object, so you can maintain the chainability of diffrent functions.

Solution 4:

Hmm, perhaps use

var1 = $(this)[0].MyFunction();alert(var1);

But I'm not sure if that is what you want or if your code works at all. What are you trying to achieve? Are you sure you want to call this.each()?

Like the others said, jQuery returns jQuery objects in most cases, and accessing the actual object can be accomplished using an indexer [] or the get method.

Post a Comment for "Jquery Return Value"