为什么jquery插件函数总是返回对象而不是字符串? [英] why jquery plugin function is always returning object instead of a string?
问题描述
这是我的自定义jquery插件的代码:
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);
当我运行此代码时:
$(document).ready(function() {
$("#div").initPlugin();
alert($("#div").getmyValue());
});
返回的值不是假定的普通字符串,而是一个对象($(#div)返回)
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 ?
推荐答案
因为每个
的返回值是您在其上调用每个
的对象。函数的每个
调用的返回值用于确定是否停止循环(也就是说,迭代函数可以返回 false
停止循环 — docs links )。
Because the return value of each
is the object on which you called each
. The return value of the function each
calls is used to determine whether to stop looping (that is, the iteration function can return false
to stop looping — docs link).
从你的代码中不清楚你真正想要做什么 getmyValue
;返回你存储在jQuery实例本身的值?返回存储在第一个包含元素上的 myVal
?从所有包含的元素返回 myVal
值的数组?
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 the myVal
stored on the first contained element? Return an array of the myVal
values from all the contained elements?
如果你的意思是 myVal
:
getmyValue : function(){
// Here, `this` is the jQuery instance on which `getmyvalue` was called
return this.myVal;
},
如果你的意思是 myVal $ c第一个元素上的$ c>(注意它在典型情况下是原始DOM元素):
If you meant the myVal
on the first element (note that it's a raw DOM element in the typical case):
getmyValue : function(){
// Here, `this` is the jQuery instance on which `getmyvalue` was called.
// `this[0]` is the first matched element (a raw DOM element, typically).
// Note we check before accessing it to see if it's there, since a jQuery
// instance may have matched zero elements.
return this[0] ? this[0].myVal : undefined;
},
如果你的意思是 myVal的数组
来自所有匹配元素的值(在典型情况下,这些将是原始DOM元素):
If you meant an array of the myVal
values from all the matched elements (again, these will be raw DOM elements in the typical case):
getmyValue : function(){
// Here, `this` is the jQuery instance on which `getmyvalue` was called.
return this.map(function() {
// Here, though, `this` one of the elements wrapped by the jQuery,
// instance typically a raw DOM element. (Each of them in a loop.)
return this.myVal;
}).get();
},
...使用 map
获取jQuery包装的值数组,然后 获取
从中获取原始数组。
...which uses map
to get a jQuery-wrapped array of the values, and then get
to get the raw array from it.
这篇关于为什么jquery插件函数总是返回对象而不是字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!