这是我的自定义 jquery 插件代码:
(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") )
我想不通的是为什么返回链不起作用?
最佳答案
因为each
的返回值就是你调用each
的对象。函数each
calls的返回值用于判断是否停止循环(即迭代函数可以返回false
停止循环— docs link )。
从您的代码中不清楚您真正想在 getmyValue
中做什么;返回存储在 jQuery 实例本身上的值?返回存储在第一个包含元素上的 myVal
?从所有包含的元素中返回 myVal
值的数组?
如果您的意思是通过您的插件将 myVal
存储在 jQuery 实例上:
getmyValue : function(){
// Here, `this` is the jQuery instance on which `getmyvalue` was called
return this.myVal;
},
如果您指的是第一个元素上的 myVal
(请注意,在典型情况下它是原始 DOM 元素):
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 元素):
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();
},
关于javascript - 为什么 jquery 插件函数总是返回对象而不是字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8821537/