javascript jQuery 自动完成是否使用动态数组作为源
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13856429/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Does jQuery autocomplete work with a dynamic array as source
提问by Christopher Chiche
I am currently trying to create an autocomplete with a source that is stored in a javascript variable but this variable can be updated by another function. So, what I would like is that at each time the user updates the autocomplete field, the source
field of autocomplete is generated.
我目前正在尝试使用存储在 javascript 变量中的源创建自动完成,但该变量可以由另一个函数更新。所以,我想要的是,每次用户更新自动完成字段时,source
都会生成自动完成字段。
Here is the code I use:
这是我使用的代码:
<head>
<script>
var availableTags = ['java', 'javascript']
// can be called anytime
var addToTags = function(str){availableTags.push(str)}
$(function() {
$( "#tags" ).autocomplete({
source: availableTags
});
});
</script>
</head>
<body>
<div class="ui-widget">
<label for="tags">Tags: </label>
<input id="tags" />
</div>
</body>
Do I need to do a callback-like function?
我需要做一个类似回调的函数吗?
回答by Bergi
a source that is stored in a javascript variable but this variable can be updated by another function.
存储在 javascript 变量中的源,但该变量可以由另一个函数更新。
That should just work. If both the autocomplete and the updating function reference the same array, you can push new values at any time which will be used as soon as the array is evaluated next time (e.g. on keystroke).
那应该只是工作。如果自动完成和更新函数都引用同一个数组,您可以随时推送新值,这些值将在下次评估数组时立即使用(例如在击键时)。
I would like that at each time the user updates the autocomplete field, the source field of autocomplete is generated.
我希望每次用户更新自动完成字段时,都会生成自动完成的源字段。
That's a different one. Yes, this needs a callback function to generate the source
array dynamically, but that's simple. Have a look at the docs:
那是另一回事。是的,这需要一个回调函数来source
动态生成数组,但这很简单。看看文档:
$( "#tags" ).autocomplete({
source: function(request, resolve) {
// fetch new values with request.term
resolve(availableTags);
}
});
回答by Matanya
Just add a reset call to auto-complete in you addToTags
function:
只需在您的addToTags
函数中添加一个重置调用即可自动完成:
var addToTags = function(str){
availableTags.push(str);
$( "#tags" ).autocomplete({
source: availableTags
});
}
回答by Azad
this is very straight forward
这是非常直接的
$( "#tags" ).autocomplete('option', 'source', availableTags)
setting availableTags array wherever needed
在需要的地方设置 availableTags 数组