我发现编写一个可以在任何地方重复使用的插件更简单。我没有覆盖现有的 Ctrl+A 功能,而是使用 Ctrl+Shift+一个。这是一个例子:
// plugin to set/unset all items on pressing Ctrl-Shift-A
Selectize.define('set_all', function(options) {
var self = this;
self.onKeyUp = (function(e) {
var original = self.onKeyUp;
return function(e) {
// call original function - seems to work better calling this first
original.apply(this, arguments);
// keyboard event is in e.originalEvent; 'code' is the key code that was pressed
var code = e.originalEvent.code;
// do nothing if Ctrl-Shift-A was not selected
if (!(e.ctrlKey == true && e.shiftKey == true && code == 'KeyA')) {
return;
}
self.setValue(Object.keys(self.options));
self.focus(); // optional - maintains focus in input
};
})();
});
用法:
$('#your-input').selectize({plugins: ['set_all']});
self.focus() 调用是可选的,但它确实将焦点集中在 input 字段中,并且往往更直观。
除了self.focus(),您还可以将其更改为self.selectAll(),以便在添加所有项目后立即选择它们。如果您希望用户能够立即按 Backspace 并删除所有项目,以防他们在添加项目时出错。
您甚至可以进一步扩展插件并提供设置和未设置的功能。比如对上面插件的这个修改使用Ctrl+Shift+A来设置所有项目,Ctrl +Shift+S 取消设置所有项目:
// plugin to set/unset all items on pressing Ctrl-Shift-A / Ctrl-Shift-S
Selectize.define('set_all', function(options) {
var self = this;
self.onKeyUp = (function(e) {
var original = self.onKeyUp;
return function(e) {
// call original function - seems to work better calling this FIRST
original.apply(this, arguments);
// keyboard event is in e.originalEvent; 'code' is the key code that was pressed
var code = e.originalEvent.code;
// do nothing if Ctrl-Shift-A/S was not selected
if (!(e.ctrlKey == true && e.shiftKey == true && (code == 'KeyA' || code == 'KeyS'))) {
return;
}
// if 'A' was pressed set and select all items; if 'S' was pressed unset all items
if (code == 'KeyA') {
self.setValue(Object.keys(self.options));
self.focus();
} else {
self.clear();
}
};
})();
});
请注意,我还调用了原始的 onKeyUp 函数,因此它的过滤功能仍然可以按预期工作。出于某种原因,在我的修改之前调用 prior 效果最好。如果我将setValue()/clear() 调用放在return 语句所在的位置,则选择/取消选择似乎只能工作一次。