views:

54

answers:

4

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?

A: 

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

Machiel
+1  A: 

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

Justin Ethier
Thanks, syntax "jQuery.fn.extend" helps me. P.S. You forgot "fn" in answer.
Anton
Good Catch, thanks! I was looking at the isArray example in the jQuery source code, but forgot that isArray is a "static" call that would not need the fn.
Justin Ethier
A: 

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.

mnemosyn
Did not know you could use the get method for this - could you please post an example?
Justin Ethier
For example you could write `$(".someClass").get(0);`. Or am I mistaken here?
mnemosyn
A: 

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);
Crozin