jQueryUI Autocomplete-Widget:我想将一个函数绑定到菜单小部件的选择事件
我有以下使用 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("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 方法并将函数绑定到 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);
}
}));
I have the following script using the jQueryUI autocomplete widget. It calls some function whenever a menu item in the selection box is being selected:
<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>
This works nicely. But I need this method in a multiple of instances of the autocomplete widget, so I prefer extending the autocomplete widget using the widget factory.
This works nicely whenever I want to override methods of the autocomplete plugin:
$.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);
}
}));
However, I have no clue how to do that for the underlying menu widget.
I tried to override the _init
method and binding a function to the select
event. However this does not work as I don't know how to access the bind
method of the menu-widget (or this menu widget is not yet there at this point during runtime)
$.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);
}
}));
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我想你已经很接近了;您应该覆盖
_create
而不是_init
:用法:
这是一个工作示例: http://jsfiddle.net/EWsS4/
I think you're close; you should be overriding
_create
instead of_init
:Usage:
Here's a working example: http://jsfiddle.net/EWsS4/