gpt4 book ai didi

jquery-ui - jQueryUI 自动完成小部件 : I want to bind a function to the select event of the menu widget

转载 作者:行者123 更新时间:2023-12-03 07:00:32 24 4
gpt4 key购买 nike

我有以下使用 jQueryUI 自动完成小部件的脚本。每当选择框中的菜单项被选择时,它就会调用一些函数:

<script type="text/javascript">
$(function() {
$( "#tags" ).autocomplete({
source: [ "ActionScript", "AppleScript", "Asp"],
select: function() {
console.log("Element has been selected");
}
});
});
</script>

<div class="ui-widget">
<label for="tags">Tags: </label>
<input id="tags">
</div>

这个效果很好。但我需要在自动完成小部件的多个实例中使用此方法,因此我更喜欢使用 widget factory 扩展自动完成小部件。 .

每当我想覆盖自动完成插件的方法时,这都很好用:

$.widget("ui.myAutocomplete", $.extend({}, $.ui.autocomplete.prototype, {
search: function( value, event ) {
// this WORKS!
console.log('overriding autocomplete.search')

return $.ui.autocomplete.prototype.search.apply(this, arguments);
}
}));

但是,我不知道如何为底层菜单小部件执行此操作。

我尝试重写 _init 方法并将函数绑定(bind)到 select 事件。但是,这不起作用,因为我不知道如何访问菜单小部件的 bind 方法(或者在运行时此时此菜单小部件尚不存在)

$.widget("ui.myAutocomplete", $.extend({}, $.ui.autocomplete.prototype, {
_init: function() {
// this does NOT work.
this.bind('select', function() { console.log('item has been selected') })

return $.ui.autocomplete.prototype._init.apply(this, arguments);
}
}));

最佳答案

我认为你已经很接近了;您应该覆盖 _create 而不是 _init:

$.widget("ui.myAutocomplete", $.extend({}, $.ui.autocomplete.prototype, {
_create: function() {
// call autocomplete's default create method:
$.ui.autocomplete.prototype._create.apply(this, arguments);

// this.element is the element the widget was invoked with
this.element.bind("autocompleteselect", this._select);
},
_select: function(event, ui) {
// Code to be executed upon every select.
}
}));

用法:

$("input").myAutocomplete({
/* snip */
});

这是一个工作示例:http://jsfiddle.net/EWsS4/

关于jquery-ui - jQueryUI 自动完成小部件 : I want to bind a function to the select event of the menu widget,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6111792/

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