tha*_*bit 16 jquery-ui autocomplete jquery-ui-autocomplete
我使用jQuery UI的自动完成程序与创建它的方式略有不同.
基本上我想保留所有相同的功能,唯一的区别是当出现建议框时,我不会在用户进行选择时隐藏建议框,我也不希望该选择填充输入框.autocomplete附加到.
所以,我一直在阅读jQuery UI文档,看来有一种方法可以禁用Select:和Close:事件,但我发现他们解释它的方式非常混乱,因此,这就是为什么我我在这里寻求帮助.
我的jQuery
$( "#comment" ).autocomplete({
source: "comments.php",
minLength: 4,
// Attempt to remove click/select functionality - may be a better way to do this
select: function( event, ui ) {
return false;
},
// Attempt to add custom Class to the open Suggestion box - may be a better way
open : function (event, ui) {
$(this).addClass("suggestion-box");
},
// Attempt to cancel the Close event, so when someone makes a selection, the box does not close
close : function (event, ui) {
return false;
}
});
Run Code Online (Sandbox Code Playgroud)
官方jQuery UI文档
从菜单中选择项目时触发; ui.item指的是所选项目.select的默认操作是将文本字段的值替换为所选项的值.取消此事件可防止更新值,但不会阻止菜单关闭.
代码示例
Supply a callback function to handle the select event as an init option.
$( ".selector" ).autocomplete({
select: function(event, ui) { ... }
});
Bind to the select event by type: autocompleteselect.
$( ".selector" ).bind( "autocompleteselect", function(event, ui) {
...
});
Run Code Online (Sandbox Code Playgroud)
混乱
令我困惑的是,他们似乎建议删除.autocomplete并替换为.bind("autocompleteselect") - 这将完全禁用自动完成功能?
非常感谢您提供任何帮助.
cor*_*lla 19
从安德鲁斯解决方案中获取灵感,我找到了一种方法,可以在选择时保持自动完成开放,而对核心功能的影响较小:
var selected; //flag indicating a selection has taken place
var $input = $("input").autocomplete({
source: ['Hello', 'Goodbye', 'Foo', 'Bar'],
select: function( event, ui ) {
selected = true;
}
});
//Override close method - see link below for details
(function(){
var originalCloseMethod = $input.data("autocomplete").close;
$input.data("autocomplete").close = function(event) {
if (!selected){
//close requested by someone else, let it pass
originalCloseMethod.apply( this, arguments );
}
selected = false;
};
})();
Run Code Online (Sandbox Code Playgroud)
所以想法是在适当时使用中性闭合方法,如选择标志所示.在全球名称空间中选择标志可能不是最好的主意,但这是其他人改进的:-).
And*_*ker 12
使用的第二种语法.bind()只是将事件处理程序附加到jQueryUI的自定义事件的另一种方法.这与在窗口小部件选项中定义事件处理程序完全相同(使用select: function(event, ui) { })
想象一下,如果页面上有多个自动完成小部件,并且您希望在其中任何一个引发"select"事件时执行相同的功能,例如:
$(".autocomplete").bind("autocompleteselect", function(event, ui) {
/* Will occur when any element with an autocomplete widget fires the
* autocomplete select event.
*/
});
Run Code Online (Sandbox Code Playgroud)
至于取消select活动,你有正确的.然而,取消这一close事件有点困难; 看起来从事件处理程序返回false将不起作用(close在菜单实际关闭后触发).您可以执行一些hackery,只需select用您自己的函数替换该函数:
var $input = $("input").autocomplete({
source: ['Hello', 'Goodbye', 'Foo', 'Bar']
});
$input.data("autocomplete").menu.options.selected = function(event, ui) {
var item = ui.item.data( "item.autocomplete" );
$input.focus();
};
Run Code Online (Sandbox Code Playgroud)
这是一个有效的例子:http://jsfiddle.net/ZGmyp/
我不确定覆盖事件的后果是什么,但在简单的例子中看起来并没有发生任何疯狂的事情.我会说这是一种不自然的小部件使用,所以可能会有意想不到的后果.