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

Jac*_*ack 4 tags jquery autocomplete 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开始?

jmo*_*253 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()));
}
Run Code Online (Sandbox Code Playgroud)

复制了该函数并将其粘贴到.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()));
}
Run Code Online (Sandbox Code Playgroud)

例:

$('#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()));
    }
});
Run Code Online (Sandbox Code Playgroud)