gpt4 book ai didi

javascript - 在 jQuery 插件/Javascript 中产生一个变量

转载 作者:行者123 更新时间:2023-11-29 22:27:33 25 4
gpt4 key购买 nike

我想创建一个可以附加到文本框的 jQuery 插件,当用户输入某个组合键后,可以调用一个回调函数,并根据输入的组合键设置一个变量。我来自 Ruby 背景,我不确定这在 Javascript/jQuery 中是否可行。这是一个例子:

$('textbox').attach_my_plugin(function(){|key_combo_var|
// do something with key_combo_var...
});

我将如何实现这一目标? B 计划是将 key_combo_var 粘贴到元素的 .data() 中。还有比这更好的方法吗?

最佳答案

这是完全可能的。尽管您没有提供太多细节(什么特定操作?)。

这是一个好的开始 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)"); }
});

关于javascript - 在 jQuery 插件/Javascript 中产生一个变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8601032/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com