Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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).MyFunction();alert(var1);

I got an [object], but not the "test".

How to allow jquery plugin return a some value?

like image 843
Anton Avatar asked Mar 13 '10 14:03

Anton


2 Answers

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 [].

like image 179
Justin Ethier Avatar answered Oct 28 '22 11:10

Justin Ethier


Here is once again your code:

jQuery.fn.MyFunction = function() { #1
   return this.each(function() {    #2
      return "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() {
    return this.each(function() {
        return "abc";
    });
};

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

var MyFunctionResult = $(document).MyFunction();
var AnotherFunctionResult = $(document).AnotherFunction();

alert(MyFunctionResult);
alert(AnotherFunctionResult);
like image 6
Crozin Avatar answered Oct 28 '22 12:10

Crozin