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?
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 []
.
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.
MyFunction
which is a function for every jQuery object.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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With