从 jQuery 插件调用方法函数
给出以下 jQuery 插件:
(function($) {
$.fn.prefCookie = function(method) {
var options = {
cookieName : 'prefs',
actionType : 'click',
key : '',
value : false
}
var $obj;
var methods = {
init : function(config) {
return this.each(function() {
if(config) { $.extend(options, config) }
$obj = $(this);
options.value ?
$obj.bind(options.actionType,helpers.setPref) :
$obj.bind(options.actionType,helpers.togglePref) ;
});
},
anotherFunction : function() {
console.log('you did it!');
}
}
var helpers = {
togglePref : function() {
},
setPref : function() {
}
}
if (methods[method] && method.toLowerCase() != 'init') {
return methods[method].apply(this, Array.prototype.slice.call(arguments, 1));
} else if (typeof method === 'object' || !method) {
return methods.init.apply(this, arguments);
} else {
$.error( 'Method "' + method + '" does not exist in the Pref Cookie plugin!');
}
}
})(jQuery);
如何在不将插件附加到任何东西的情况下使用 anotherFunction
。我想做 $.prefCookie.anotherFunction
或其他东西,但它不起作用。有什么建议吗?
Give the following jQuery plugin:
(function($) {
$.fn.prefCookie = function(method) {
var options = {
cookieName : 'prefs',
actionType : 'click',
key : '',
value : false
}
var $obj;
var methods = {
init : function(config) {
return this.each(function() {
if(config) { $.extend(options, config) }
$obj = $(this);
options.value ?
$obj.bind(options.actionType,helpers.setPref) :
$obj.bind(options.actionType,helpers.togglePref) ;
});
},
anotherFunction : function() {
console.log('you did it!');
}
}
var helpers = {
togglePref : function() {
},
setPref : function() {
}
}
if (methods[method] && method.toLowerCase() != 'init') {
return methods[method].apply(this, Array.prototype.slice.call(arguments, 1));
} else if (typeof method === 'object' || !method) {
return methods.init.apply(this, arguments);
} else {
$.error( 'Method "' + method + '" does not exist in the Pref Cookie plugin!');
}
}
})(jQuery);
How can anotherFunction
without attaching the plugin to anything. I'd like to do $.prefCookie.anotherFunction
or something, but it doesn't work. Any suggestions?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
$('您的选择器').prefCookie('anotherFunction');
应该这样做。如果您需要将任何参数传递给
anotherFunction
,只需将它们添加到字符串'anotherFunction'
后面即可。$('your selector').prefCookie('anotherFunction');
should do it.If you need to pass any parameters to
anotherFunction
, just add them after the string'anotherFunction'
.看起来您已经将其设置为处理通过字符串传入的方法调用。
如果您想按照您所说的
$.prefCookie.anotherFunction
执行此操作(这是不同的,因为没有与之关联的 jQuery 集合),请尝试类似...jsFiddle。
It looks like you have set it up to handle the method call passed in by string.
If you want to do it as you say
$.prefCookie.anotherFunction
(which is different because there is no jQuery collection associated with it), try something like...jsFiddle.