これは完全に可能です。あなたは多くの詳細を与えていませんが(何が特定のアクションですか?)
良いスタートがサイトこの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
正確です。このメカニズムは*コールバック*と呼ばれます。例えば、jQuery自体は、アニメーションの終了後にユーザーがコードを実行できるようにするため、またはajaxリクエストが成功したときに、これを多く使用します。この[記事](http://jquery-howto.blogspot.com/2009/11/create-callback-functions-for-your.html)とこの他の[質問](http://stackoverflow.com/questions)を参照してください。/483073/getting-a-better-of-callback-functions-in-javascriptを参照してください)。 –