如何改进jQuery“Tag-It”自动完成功能?

时间:2011-07-27 12:13:59

标签: jquery autocomplete tags tag-it

我喜欢jQuery的Tag-It插件,但是如果我将它设置为自动完成,它并不总是以我想要的方式工作。

这是一个例子。

我的自动完成阵列包括“Pink Lady Apple”,“Granny Smith Apple”,“Golden Delicious Apple”和“Apple”。

如果我输入“Apple”,则不建议Pink Lady,Granny Smith或Golden Delicious。它只表明Apple。有没有办法可以改变这一点,以便它也可以扫描包含Apple但不是以Apple开头的标签?

3 个答案:

答案 0 :(得分:6)

我遇到了同样的问题,所以我使用@ Ravindra的提示(+1 BTW)来查看我是否可以对插件进行反向工程并找出tagSource函数预期返回的内容。

tagSource函数返回一个布尔值。如果availableTags数组中的标记显示在自动完成列表中,则返回True。返回False表示不应显示标记。

这是默认的tagSource函数,它使用indexOf来确定到目前为止输入的文本是否与availableTags数组中标记的开头匹配:

原创,默认功能:

tagSource: function(search, showChoices) {
    var filter = search.term.toLowerCase();
    var choices = $.grep(this.options.availableTags, function(element) {
       // Only match autocomplete options that begin with the search term.
       // (Case insensitive.)
       return (element.toLowerCase().indexOf(filter) === 0);
    });
    showChoices(this._subtractArray(choices, this.assignedTags()));
}

复制函数并将其粘贴到.tagit函数中,因此它被作为传递给jQuery tagit初始化函数的参数之一包含在内。然后我修改它以使用match方法,该方法使用模式匹配来返回与模式匹配的字符串部分。如果匹配返回null,请不要在列表中显示它。如果它返回任何其他内容,则在列表中显示标记:

作为参数传入的修改函数:

tagSource: function(search, showChoices) {
    var filter = search.term.toLowerCase();
    var choices = $.grep(this.options.availableTags, function(element) {
       // Only match autocomplete options that begin with the search term.
       // (Case insensitive.)
       //return (element.toLowerCase().indexOf(filter) === 0);
       console.info(element.toLowerCase().match(filter) + " : " + element + " : " + filter);
       return (element.toLowerCase().match(filter) !== null);
    });
    showChoices(this._subtractArray(choices, this.assignedTags()));
}

示例:

$('#tagged').tagit({
    onTagRemoved: function() {
        alert("Removed tag");
    },

    availableTags: [ "one" , "two one" , "three" , "four" , "five" ],

    // override function to modify autocomplete behavior
    tagSource: function(search, showChoices) {
        var filter = search.term.toLowerCase();
        var choices = $.grep(this.options.availableTags, function(element) {
           // Only match autocomplete options that begin with the search term.
           // (Case insensitive.)
           //return (element.toLowerCase().indexOf(filter) === 0);
           console.info(element.toLowerCase().match(filter) + " : " + element + " : " + filter);
           return (element.toLowerCase().match(filter) !== null);
        });
        showChoices(this._subtractArray(choices, this.assignedTags()));
    }
});

答案 1 :(得分:4)

tag-it tagSource 属性对我有用。我正在使用http://aehlke.github.com/tag-it/

答案 2 :(得分:0)

Tag-It继承了wai-aria实现的自动完成功能。默认情况下,它只知道三种状态:

无 - 根本没有完成 内联 - 从......开始 列表 - 全部可用

因此,如果不扩展标记 - 它使用不同的自动完成方法,这是不可能的。

有关WAI-ARIA的更多信息,请参阅此处:

http://www.w3.org/WAI/intro/aria

http://test.cita.illinois.edu/aria/