这是完全可能的。虽然你没有提供太多细节(有什么特定的行动?)。
良好的开端是这个jQuery plugin boilerplate
该网站提供了一种方法,开始创建自己的插件。这件事很好记录,所以如果你可以阅读JavaScript/jQuery代码,它不应该太难。
如果您提供了更多关于您想要做什么的细节,我可以帮助您进一步实施它,但现在它有点太模糊。
作为例子
我已经使用了样板应该做你以后找什么插件的实例创建。至少这会给你一个好的开始。
当你按下ctrl-shift-a时,它基本上会执行回调。
您可以在jsfiddle上进行测试。
;(function ($, window, document, undefined) {
var pluginName = 'callbackOnKey',
defaults = {
// define a default empty callback as default
callback: function() {}
};
function Plugin(element, options) {
this.element = element;
this.options = $.extend({}, defaults, options) ;
this._defaults = defaults;
this._name = pluginName;
this.init();
}
Plugin.prototype.init = function() {
var $this = $(this.element),
keydownHandler = function(e) {
// in here, 'this' is the plugin instance thanks to $.proxy
// so i can access the options property (this.options.callback)
// if key combination is CTRL-SHIFT-a
if (e.ctrlKey && e.shiftKey && e.which === 65 && this.options.callback) {
// execute the callback
this.options.callback.apply(this);
}
};
// bind the handler on keydown
// i use $.proxy to change the context the handler will be executed
// with (what will be 'this' in the handler). by default it would
// have been the input element, now it will be the plugin instance
$this.bind('keydown', $.proxy(keydownHandler, this));
};
$.fn[pluginName] = function (options) {
return this.each(function() {
if (!$.data(this, 'plugin_' + pluginName)) {
$.data(this, 'plugin_' + pluginName, new Plugin(this, options));
}
});
}
})(jQuery, window, document);
// use the plugin and pass a callback function
$('#myinput').callbackOnKey({
callback: function() { alert("It's working :o)"); }
});
为了清楚起见,更新了我的问题。看着样板,看起来插件用户可以在插件中指定'function(key_combo_var){...}'作为选项,然后从我的插件代码中随后可以随意调用set变量来调用该函数。它是否正确?一旦我有空,我会尝试一下。 – Suan 2011-12-22 23:02:28
没错。这种机制被称为* callbacks *。例如,jQuery本身使用了很多,例如,允许用户在动画完成后执行一些代码,或者当ajax请求成功时执行一些代码。看到这[文章](http://jquery-howto.blogspot.com/2009/11/create-callback-functions-for-your.html)和这其他[问题](http://stackoverflow.com/questions/483073 /越来越了解回调函数在JavaScript中)的更多信息。 – 2011-12-22 23:32:53