here is my code for a custom jquery plugin :
(function($){
$.fn.extend({
getmyValue : function(){
return this.each(function() {
return this.myVal;
});
},
initPlugin : function(){
return this.each(function() {
this.myVal='Some results';
});
}
});
})(jQuery);
when i run this code :
$(document).ready(function() {
$("#div").initPlugin();
alert($("#div").getmyValue());
});
the returned value is not a plain string as supposed but an object ( $(“#div”) is returned )
what i can’t figure out is why the return chaining is not working ?
Because the return value of
eachis the object on which you calledeach. The return value of the functioneachcalls is used to determine whether to stop looping (that is, the iteration function can returnfalseto stop looping — docs link).It’s unclear from your code what you really want to do in
getmyValue; return a value you’ve stored on the jQuery instance itself? Return themyValstored on the first contained element? Return an array of themyValvalues from all the contained elements?If you meant a
myValstored on the jQuery instance by your plugin:If you meant the
myValon the first element (note that it’s a raw DOM element in the typical case):If you meant an array of the
myValvalues from all the matched elements (again, these will be raw DOM elements in the typical case):…which uses
mapto get a jQuery-wrapped array of the values, and thengetto get the raw array from it.