jQuery自动完成是否将动态数组作为源工作 [英] Does jQuery autocomplete work with a dynamic array as source

查看:93
本文介绍了jQuery自动完成是否将动态数组作为源工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我当前正在尝试使用存储在javascript变量中的源创建自动完成功能,但是此变量可以由另一个函数更新.因此,我希望每次用户更新自动完成字段时,都会生成自动完成的source字段.

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.

这是我使用的代码:

<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?

推荐答案

存储在javascript变量中的源,但是此变量可以由另一个函数更新.

a source that is stored in a javascript variable but this variable can be updated by another function.

那应该就可以了.如果自动完成功能和更新功能都引用同一数组,则您可以随时推送新值,该值将在下次评估该数组时(例如,在击键时)立即使用.

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.

那是另一回事.是的,这需要一个回调函数来动态生成source数组,但这很简单.看看文档:

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:

$( "#tags" ).autocomplete({
    source: function(request, resolve) {
        // fetch new values with request.term
        resolve(availableTags);
    }
});

这篇关于jQuery自动完成是否将动态数组作为源工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆