如何在第一次按键时让typeAhead每次都能正常工作

时间:2013-10-25 07:45:37

标签: javascript jquery json onkeyup typeahead

我有一个typeAhead函数(使用twitter typeahead库),当我输入第一个字母时,它会加载一组json文件。

这些json文件名为'words_a.json','words_b.json'等。它们包含以字母A,B,C等开头的每个荷兰语单词。

我面临的问题是:

1)只要在'#search-box'中键入第一个字符,输入字段的焦点就会丢失。这是由于'jquery.one()'功能。有什么方法可以阻止这种情况吗?

2)我不能使用'jquery.keypress()',因为这会使用您键入的每个字符调用json文件。我只想为第一个字符调用json文件。它应该加载以该字符开头的所有单词。

3)'jquery.one()'的另一个缺点是,一旦找到了我要找的单词,我就想开始寻找一个新单词。所以我删除了输入字段中的每个字符。但是,它不会为您键入的第一个字符加载另一个json文件,因为'jquery.one()'已经触发了一次并且已经加载了一个json文件。有没有办法避免这种行为,并在从输入字段中删除所有字符后再次启动该功能?

这是我的代码:

<script>
        $(document).ready(function() {

                $('#search-box').one('keyup', function() {
                    var character = $('#search-box').val().substring(0, 1);
                    var chr = character.toLowerCase();
                    //console.log(chr);

                    $.getJSON('words/words_' + chr + '.json', function(wordsArray){
                        //console.log(wordsArray);
                        $('#search-box').typeahead({
                        name: 'words',
                        //local: [],
                        local: wordsArray,
                        limit: 10
                        }); // close typeAhead function
                    }); // close getJSON
                }); // close search-box keyup function

            $('#search-box').bind('typeahead:selected', function(obj, value) {
                //console.log(value.value);
                $('#resultaten').append('<a href="#" onClick="speak(&quot;'+value.value+'&quot;, &quot;nl&quot;)">' + value.value + '\
        &nbsp;<img src="img/speaker.png" alt="speaker"/></a><br />');

            }); //close typeahead selected selected function
            $('#search-box').typeahead().destroy();
        }); // close document.ready
</script>


<form class="form-search">
     <h2 class="form-search-heading">Zoek in OpenTaal woordenlijst</h2>
     <input type="text" class="input-block-level" placeholder="Zoekterm" id="search-box">
     <div id="resultaten"></div>
</form>

1 个答案:

答案 0 :(得分:0)

您可能需要查看此内容:http://oak.cs.ucla.edu/cs144/projects/javascript/suggest1.html

它有一个JSON列表,它确实使用了按键。但是,如果它仅适用于第一个角色,它还有什么用呢?说这些是名字,你有10&#34;史密斯&#34;?你可能想输入&#34;史密斯,&#34;得到他们中的第一个。

无论如何,你总是可以添加一个&#34; if&#34;计算文本框中值的长度的语句。例如,如果您$(this).val().length > 1,则不做任何事情。 else,你继续检查。