我编写了一个 jq-plugin,我首先要在其中初始化选定的元素(所有元素)。 稍后在代码中我想获取由方法生成的字符串。但它返回的只是对象,而不是我的字符串。
我在互联网上做了很多研究,但我不知道如何一方面使插件“可链接”,另一方面“返回任何值”。
你觉得怎么样?
(function($){
var methods = {
init: function(val){
// Actions to initialize ALL selected Elements
}
,
returner: function(val){
alert('working with every selected element: '+$(this).width());
// return anything
return 'STRING PRODUCED BY THIS FUNCTION!';
}
}
$.fn.myplug = function(method){
var args = arguments;
var init = 'init-myplug';
return this.each(function(){
var is_init = $(this).data(init);
if (is_init && methods[method]){
return methods[method].apply($(this), Array.prototype.slice.call(args, 1));
} else if (!is_init && (typeof method === 'object' || !method)){
$(this).data(init, true);
return methods.init.apply($(this), Array.prototype.slice.call(args, 0));
}
});
};
})(jQuery);
$('.selects_5_elements').myplug(); // init
$('.selects_5_elements').myplug('returner'); // get the string
最佳答案
第一步是收集您的方法的结果。目前,您尝试通过 each 回调返回该方法的结果,这是行不通的(each 回调中的返回值用于跳出循环)。
我建议将所有结果收集在一个数组中,如下所示:
var results = [];
this.each(function(){
var is_init = $(this).data(init);
if (is_init && methods[method]){
results.push(methods[method].apply($(this), Array.prototype.slice.call(args, 1)));
} else if (!is_init && (typeof method === 'object' || !method)){
$(this).data(init, true);
results.push(methods.init.apply($(this), Array.prototype.slice.call(args, 0)));
}
});
此时您可以简单地返回结果数组。但是,如果您希望允许某些方法可链接,而其他方法则返回方法调用的结果,那么您需要检查方法名称来决定返回什么值。
if (method == 'returner')
return results;
else
return this;
另外,请注意,我们在这里返回一个数组,而不是一个字符串。原因是,将为每个与选择器匹配的元素调用您的方法。因此,如果您有五个匹配元素,您将获得一个包含 5 个字符串的数组。
如果您确实只想返回单个字符串,那么您需要决定如何处理所有重复项。您想将所有字符串连接在一起吗?或者只返回第一个字符串?还是只有最后一根弦?所有选项都很容易做到 - 您选择哪个将取决于您的要求。
关于jquery插件方法返回值不是对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15473951/