我在表单中的字段中使用此自动完成功能,该功能可以正常工作:

我的表格栏位:

<input type="text" class="form-control" name="palabrasClave" id="listadoTags">
<div id="resultado"></div>


我的JS代码:

var root = document.location.hostname;
var archivo = "/includes/autocompletarTags.php";

$( "#listadoTags" ).autocomplete({
  source: root+archivo,
  appendTo: "#resultado",
  minLength: 2
});


问题是当我已经有一个单词时,我想用逗号分隔它并继续添加标签...我该怎么做?

我想在同一字段中有几个标签...

最佳答案

!function($){"use strict";var TagSuggest=function(element,options){var ms=this,defaults={allowFreeEntries:!0,cls:"",data:null,dataUrlParams:{},disabled:!1,displayField:"name",editable:!0,emptyText:function(){return cfg.editable?"Type or click here":"Click here"},emptyTextCls:"tag-empty-text",expanded:!1,expandOnFocus:function(){return!cfg.editable},groupBy:null,hideTrigger:!1,highlight:!0,id:function(){return"tag-ctn-"+$('div[id^="tag-ctn"]').length},infoMsgCls:"",inputCfg:{},invalidCls:"tag-ctn-invalid",matchCase:!1,maxDropHeight:290,maxEntryLength:null,maxEntryRenderer:function(e){return"Please reduce your entry by "+e+" character"+(e>1?"s":"")},maxSuggestions:null,maxSelection:10,maxSelectionRenderer:function(e){return"You cannot choose more than "+e+" item"+(e>1?"s":"")},method:"POST",minChars:0,minCharsRenderer:function(e){return"Please type "+e+" more character"+(e>1?"s":"")},name:null,noSuggestionText:"No suggestions",preselectSingleSuggestion:!0,renderer:null,required:!1,resultAsString:!1,resultsField:"results",selectionCls:"",selectionPosition:"inner",selectionRenderer:null,selectionStacked:!1,sortDir:"asc",sortOrder:null,strictSuggest:!1,style:"",toggleOnClick:!1,typeDelay:400,useTabKey:!1,useCommaKey:!0,useZebraStyle:!0,value:null,valueField:"id",width:function(){return $(this).width()}},conf=$.extend({},options),cfg=$.extend(!0,{},defaults,conf);$.isFunction(cfg.emptyText)&&(cfg.emptyText=cfg.emptyText.call(this)),$.isFunction(cfg.expandOnFocus)&&(cfg.expandOnFocus=cfg.expandOnFocus.call(this)),$.isFunction(cfg.id)&&(cfg.id=cfg.id.call(this)),this.addToSelection=function(e,t){if(!cfg.maxSelection||_selection.length<cfg.maxSelection){$.isArray(e)||(e=[e]);var s=!1;$.each(e,function(e,t){-1===$.inArray(t[cfg.valueField],ms.getValue())&&(_selection.push(t),s=!0)}),!0===s&&(self._renderSelection(),this.empty(),!0!==t&&$(this).trigger("selectionchange",[this,this.getSelectedItems()]))}},this.clear=function(e){this.removeFromSelection(_selection.slice(0),e)},this.collapse=function(){!0===cfg.expanded&&(this.combobox.detach(),cfg.expanded=!1,$(this).trigger("collapse",[this]))},this.disable=function(){this.container.addClass("tag-ctn-disabled"),cfg.disabled=!0,ms.input.attr("disabled",!0)},this.empty=function(){this.input.removeClass(cfg.emptyTextCls),this.input.val("")},this.enable=function(){this.container.removeClass("tag-ctn-disabled"),cfg.disabled=!1,ms.input.attr("disabled",!1)},this.expand=function(){!cfg.expanded&&(this.input.val().length>=cfg.minChars||this.combobox.children().size()>0)&&(this.combobox.appendTo(this.container),self._processSuggestions(),cfg.expanded=!0,$(this).trigger("expand",[this]))},this.isDisabled=function(){return cfg.disabled},this.isValid=function(){return!1===cfg.required||_selection.length>0},this.getDataUrlParams=function(){return cfg.dataUrlParams},this.getName=function(){return cfg.name},this.getSelectedItems=function(){return _selection},this.getRawValue=function(){return ms.input.val()!==cfg.emptyText?ms.input.val():""},this.getValue=function(){return $.map(_selection,function(e){return e[cfg.valueField]})},this.removeFromSelection=function(e,t){$.isArray(e)||(e=[e]);var s=!1;$.each(e,function(e,t){var n=$.inArray(t[cfg.valueField],ms.getValue());n>-1&&(_selection.splice(n,1),s=!0)}),!0===s&&(self._renderSelection(),!0!==t&&$(this).trigger("selectionchange",[this,this.getSelectedItems()]),cfg.expandOnFocus&&ms.expand(),cfg.expanded&&self._processSuggestions())},this.setData=function(e){cfg.data=e,self._processSuggestions()},this.setName=function(e){cfg.name=e,ms._valueContainer&&(ms._valueContainer.name=e)},this.setValue=function(data){var values=data,items=[];$.isArray(data)||("string"==typeof data?data.indexOf("[")>-1?values=eval(data):data.indexOf(",")>-1&&(values=data.split(",")):values=[data]),$.each(_cbData,function(e,t){$.inArray(t[cfg.valueField],values)>-1&&items.push(t)}),items.length>0&&this.addToSelection(items)},this.setDataUrlParams=function(e){cfg.dataUrlParams=$.extend({},e)};var _selection=[],_comboItemHeight=0,_timer,_hasFocus=!1,_groups=null,_cbData=[],_ctrlDown=!1,self={_displaySuggestions:function(e){ms.combobox.empty();var t=0,s=0;if(null===_groups)self._renderComboItems(e),t=_comboItemHeight*e.length;else{for(var n in _groups)s+=1,$("<div/>",{class:"tag-res-group",html:n}).appendTo(ms.combobox),self._renderComboItems(_groups[n].items,!0);t=_comboItemHeight*(e.length+s)}t<ms.combobox.height()||t<=cfg.maxDropHeight?ms.combobox.height(t):t>=ms.combobox.height()&&t>cfg.maxDropHeight&&ms.combobox.height(cfg.maxDropHeight),1===e.length&&!0===cfg.preselectSingleSuggestion&&ms.combobox.children().filter(":last").addClass("tag-res-item-active"),0===e.length&&""!==ms.getRawValue()&&(self._updateHelper(cfg.noSuggestionText),ms.collapse())},_getEntriesFromStringArray:function(e){var t=[];return $.each(e,function(e,s){var n={};n[cfg.displayField]=n[cfg.valueField]=$.trim(s),t.push(n)}),t},_highlightSuggestion:function(e){var t=ms.input.val()!==cfg.emptyText?ms.input.val():"";return 0===t.length?e:e=!0===cfg.matchCase?e.replace(new RegExp("("+t+")(?!([^<]+)?>)","g"),"<em>$1</em>"):e.replace(new RegExp("("+t+")(?!([^<]+)?>)","gi"),"<em>$1</em>")},_moveSelectedRow:function(e){var t,s,n,i;cfg.expanded||ms.expand(),t=ms.combobox.find(".tag-res-item"),s="down"===e?t.eq(0):t.filter(":last"),(n=ms.combobox.find(".tag-res-item-active:first")).length>0&&("down"===e?(0===(s=n.nextAll(".tag-res-item").first()).length&&(s=t.eq(0)),i=ms.combobox.scrollTop(),ms.combobox.scrollTop(0),s[0].offsetTop+s.outerHeight()>ms.combobox.height()&&ms.combobox.scrollTop(i+_comboItemHeight)):(0===(s=n.prevAll(".tag-res-item").first()).length&&(s=t.filter(":last"),ms.combobox.scrollTop(_comboItemHeight*t.length)),s[0].offsetTop<ms.combobox.scrollTop()&&ms.combobox.scrollTop(ms.combobox.scrollTop()-_comboItemHeight))),t.removeClass("tag-res-item-active"),s.addClass("tag-res-item-active")},_processSuggestions:function(e){var t=null,s=e||cfg.data;if(null!==s){if("function"==typeof s&&(s=s.call(ms)),"string"==typeof s&&s.indexOf(",")<0){$(ms).trigger("beforeload",[ms]);var n=$.extend({query:ms.input.val()},cfg.dataUrlParams);return void $.ajax({type:cfg.method,url:s,data:n,success:function(e){t="string"==typeof e?JSON.parse(e):e,self._processSuggestions(t),$(ms).trigger("load",[ms,t])},error:function(){throw"Could not reach server"}})}_cbData="string"==typeof s&&s.indexOf(",")>-1?self._getEntriesFromStringArray(s.split(",")):s.length>0&&"string"==typeof s[0]?self._getEntriesFromStringArray(s):s[cfg.resultsField]||s,self._displaySuggestions(self._sortAndTrim(_cbData))}},_render:function(e){$(ms).trigger("beforerender",[ms]);var t=$.isFunction(cfg.width)?cfg.width.call(e):cfg.width;switch(ms.container=$("<div/>",{id:cfg.id,class:"tag-ctn "+cfg.cls+(!0===cfg.disabled?" tag-ctn-disabled":"")+(!0===cfg.editable?"":" tag-ctn-readonly"),style:cfg.style}).width(t),ms.container.focus($.proxy(handlers._onFocus,this)),ms.container.blur($.proxy(handlers._onBlur,this)),ms.container.keydown($.proxy(handlers._onKeyDown,this)),ms.container.keyup($.proxy(handlers._onKeyUp,this)),ms.input=$("<input/>",$.extend({id:"tag-input-"+$('input[id^="tag-input"]').length,type:"text",class:cfg.emptyTextCls+(!0===cfg.editable?"":" tag-input-readonly"),value:cfg.emptyText,readonly:!cfg.editable,disabled:cfg.disabled},cfg.inputCfg)).width(t-(cfg.hideTrigger?16:42)),ms.input.focus($.proxy(handlers._onInputFocus,this)),ms.input.click($.proxy(handlers._onInputClick,this)),!1===cfg.hideTrigger&&(ms.trigger=$("<div/>",{id:"tag-trigger-"+$('div[id^="tag-trigger"]').length,class:"tag-trigger",html:'<div class="tag-trigger-ico"></div>'}),ms.trigger.click($.proxy(handlers._onTriggerClick,this)),ms.container.append(ms.trigger)),ms.combobox=$("<div/>",{id:"tag-res-ctn-"+$('div[id^="tag-res-ctn"]').length,class:"tag-res-ctn "}).width(t).height(cfg.maxDropHeight),ms.combobox.on("click","div.tag-res-item",$.proxy(handlers._onComboItemSelected,this)),ms.combobox.on("mouseover","div.tag-res-item",$.proxy(handlers._onComboItemMouseOver,this)),ms.selectionContainer=$("<div/>",{id:"tag-sel-ctn-"+$('div[id^="tag-sel-ctn"]').length,class:"tag-sel-ctn"}),ms.selectionContainer.click($.proxy(handlers._onFocus,this)),"inner"===cfg.selectionPosition?ms.selectionContainer.append(ms.input):ms.container.append(ms.input),ms.helper=$("<div/>",{class:"tag-helper "+cfg.infoMsgCls}),self._updateHelper(),ms.container.append(ms.helper),$(e).replaceWith(ms.container),cfg.selectionPosition){case"bottom":ms.selectionContainer.insertAfter(ms.container),!0===cfg.selectionStacked&&(ms.selectionContainer.width(ms.container.width()),ms.selectionContainer.addClass("tag-stacked"));break;case"right":ms.selectionContainer.insertAfter(ms.container),ms.container.css("float","left");break;default:ms.container.append(ms.selectionContainer)}self._processSuggestions(),null!==cfg.value&&(ms.setValue(cfg.value),self._renderSelection()),$(ms).trigger("afterrender",[ms]),$("body").click(function(e){ms.container.hasClass("tag-ctn-bootstrap-focus")&&0===ms.container.has(e.target).length&&e.target.className.indexOf("tag-res-item")<0&&e.target.className.indexOf("tag-close-btn")<0&&ms.container[0]!==e.target&&handlers._onBlur()}),!0===cfg.expanded&&(cfg.expanded=!1,ms.expand())},_renderComboItems:function(e,t){var s=this,n="";$.each(e,function(e,i){var a=null!==cfg.renderer?cfg.renderer.call(s,i):i[cfg.displayField],o=$("<div/>",{class:"tag-res-item "+(t?"tag-res-item-grouped ":"")+(e%2==1&&!0===cfg.useZebraStyle?"tag-res-odd":""),html:!0===cfg.highlight?self._highlightSuggestion(a):a,"data-json":JSON.stringify(i)});o.click($.proxy(handlers._onComboItemSelected,s)),o.mouseover($.proxy(handlers._onComboItemMouseOver,s)),n+=$("<div/>").append(o).html()}),ms.combobox.append(n),_comboItemHeight=ms.combobox.find(".tag-res-item:first").outerHeight()},_renderSelection:function(){var e=this,t=0,s=0,n=[],i=!0===cfg.resultAsString&&!_hasFocus;ms.selectionContainer.find(".tag-sel-item").remove(),void 0!==ms._valueContainer&&ms._valueContainer.remove(),$.each(_selection,function(t,s){var a,o=null!==cfg.selectionRenderer?cfg.selectionRenderer.call(e,s):s[cfg.displayField];!0===i?a=$("<div/>",{class:"tag-sel-item tag-sel-text "+cfg.selectionCls,html:o+(t===_selection.length-1?"":",")}).data("json",s):(a=$("<div/>",{class:"tag-sel-item "+cfg.selectionCls,html:o}).data("json",s),!1===cfg.disabled&&$("<span/>",{class:"tag-close-btn"}).data("json",s).appendTo(a).click($.proxy(handlers._onTagTriggerClick,e))),n.push(a)}),ms.selectionContainer.prepend(n),ms._valueContainer=$("<input/>",{type:"hidden",name:cfg.name,value:JSON.stringify(ms.getValue())}),ms._valueContainer.appendTo(ms.selectionContainer),"inner"===cfg.selectionPosition&&(ms.input.width(0),s=ms.input.offset().left-ms.selectionContainer.offset().left,t=ms.container.width()-s-42,ms.input.width(t),ms.container.height(ms.selectionContainer.height())),_selection.length===cfg.maxSelection?self._updateHelper(cfg.maxSelectionRenderer.call(this,_selection.length)):ms.helper.hide()},_selectItem:function(e){1===cfg.maxSelection&&(_selection=[]),ms.addToSelection(e.data("json")),e.removeClass("tag-res-item-active"),!1!==cfg.expandOnFocus&&_selection.length!==cfg.maxSelection||ms.collapse(),_hasFocus?_hasFocus&&(cfg.expandOnFocus||_ctrlDown)&&(self._processSuggestions(),_ctrlDown&&ms.expand()):ms.input.focus()},_sortAndTrim:function(e){var t=ms.getRawValue(),s=[],n=[],i=ms.getValue();return t.length>0?$.each(e,function(e,n){var i=n[cfg.displayField];(!0===cfg.matchCase&&i.indexOf(t)>-1||!1===cfg.matchCase&&i.toLowerCase().indexOf(t.toLowerCase())>-1)&&(!1!==cfg.strictSuggest&&0!==i.toLowerCase().indexOf(t.toLowerCase())||s.push(n))}):s=e,$.each(s,function(e,t){-1===$.inArray(t[cfg.valueField],i)&&n.push(t)}),null!==cfg.sortOrder&&n.sort(function(e,t){return e[cfg.sortOrder]<t[cfg.sortOrder]?"asc"===cfg.sortDir?-1:1:e[cfg.sortOrder]>t[cfg.sortOrder]?"asc"===cfg.sortDir?1:-1:0}),cfg.maxSuggestions&&cfg.maxSuggestions>0&&(n=n.slice(0,cfg.maxSuggestions)),null!==cfg.groupBy&&(_groups={},$.each(n,function(e,t){void 0===_groups[t[cfg.groupBy]]?_groups[t[cfg.groupBy]]={title:t[cfg.groupBy],items:[t]}:_groups[t[cfg.groupBy]].items.push(t)})),n},_updateHelper:function(e){ms.helper.html(e),ms.helper.is(":visible")||ms.helper.fadeIn()}},handlers={_onBlur:function(){if(ms.container.removeClass("tag-ctn-bootstrap-focus"),ms.collapse(),_hasFocus=!1,""!==ms.getRawValue()&&!0===cfg.allowFreeEntries){var e={};e[cfg.displayField]=e[cfg.valueField]=ms.getRawValue(),ms.addToSelection(e)}self._renderSelection(),!1===ms.isValid()&&ms.container.addClass("tag-ctn-invalid"),""===ms.input.val()&&0===_selection.length?(ms.input.addClass(cfg.emptyTextCls),ms.input.val(cfg.emptyText)):""!==ms.input.val()&&!1===cfg.allowFreeEntries&&(ms.empty(),self._updateHelper("")),ms.input.is(":focus")&&$(ms).trigger("blur",[ms])},_onComboItemMouseOver:function(e){ms.combobox.children().removeClass("tag-res-item-active"),$(e.currentTarget).addClass("tag-res-item-active")},_onComboItemSelected:function(e){self._selectItem($(e.currentTarget))},_onFocus:function(){ms.input.focus()},_onInputClick:function(){!1===ms.isDisabled()&&_hasFocus&&!0===cfg.toggleOnClick&&(cfg.expanded?ms.collapse():ms.expand())},_onInputFocus:function(){if(!1===ms.isDisabled()&&!_hasFocus){_hasFocus=!0,ms.container.addClass("tag-ctn-bootstrap-focus"),ms.container.removeClass(cfg.invalidCls),ms.input.val()===cfg.emptyText&&ms.empty();var e=ms.getRawValue().length;!0===cfg.expandOnFocus&&ms.expand(),_selection.length===cfg.maxSelection?self._updateHelper(cfg.maxSelectionRenderer.call(this,_selection.length)):e<cfg.minChars&&self._updateHelper(cfg.minCharsRenderer.call(this,cfg.minChars-e)),self._renderSelection(),$(ms).trigger("focus",[ms])}},_onKeyDown:function(e){var t=ms.combobox.find(".tag-res-item-active:first"),s=ms.input.val()!==cfg.emptyText?ms.input.val():"";if($(ms).trigger("keydown",[ms,e]),9!==e.keyCode||!1!==cfg.useTabKey&&(!0!==cfg.useTabKey||0!==t.length||0!==ms.input.val().length))switch(e.keyCode){case 8:0===s.length&&ms.getSelectedItems().length>0&&"inner"===cfg.selectionPosition&&(_selection.pop(),self._renderSelection(),$(ms).trigger("selectionchange",[ms,ms.getSelectedItems()]),ms.input.focus(),e.preventDefault());break;case 9:case 188:case 13:e.preventDefault();break;case 17:_ctrlDown=!0;break;case 40:e.preventDefault(),self._moveSelectedRow("down");break;case 38:e.preventDefault(),self._moveSelectedRow("up");break;default:_selection.length===cfg.maxSelection&&e.preventDefault()}else handlers._onBlur()},_onKeyUp:function(e){var t,s=ms.getRawValue(),n=$.trim(ms.input.val()).length>0&&ms.input.val()!==cfg.emptyText&&(!cfg.maxEntryLength||$.trim(ms.input.val()).length<=cfg.maxEntryLength),i={};if($(ms).trigger("keyup",[ms,e]),clearTimeout(_timer),27===e.keyCode&&cfg.expanded&&ms.combobox.height(0),9===e.keyCode&&!1===cfg.useTabKey||e.keyCode>13&&e.keyCode<32)17===e.keyCode&&(_ctrlDown=!1);else switch(e.keyCode){case 40:case 38:e.preventDefault();break;case 13:case 9:case 188:if(188!==e.keyCode||!0===cfg.useCommaKey){if(e.preventDefault(),!0===cfg.expanded&&(t=ms.combobox.find(".tag-res-item-active:first")).length>0)return void self._selectItem(t);!0===n&&!0===cfg.allowFreeEntries&&(i[cfg.displayField]=i[cfg.valueField]=s,ms.addToSelection(i),ms.collapse(),ms.input.focus());break}default:_selection.length===cfg.maxSelection?self._updateHelper(cfg.maxSelectionRenderer.call(this,_selection.length)):s.length<cfg.minChars?(self._updateHelper(cfg.minCharsRenderer.call(this,cfg.minChars-s.length)),!0===cfg.expanded&&ms.collapse()):cfg.maxEntryLength&&s.length>cfg.maxEntryLength?(self._updateHelper(cfg.maxEntryRenderer.call(this,s.length-cfg.maxEntryLength)),!0===cfg.expanded&&ms.collapse()):(ms.helper.hide(),cfg.minChars<=s.length&&(_timer=setTimeout(function(){!0===cfg.expanded?self._processSuggestions():ms.expand()},cfg.typeDelay)))}},_onTagTriggerClick:function(e){ms.removeFromSelection($(e.currentTarget).data("json"))},_onTriggerClick:function(){if(!1===ms.isDisabled()&&(!0!==cfg.expandOnFocus||_selection.length!==cfg.maxSelection))if($(ms).trigger("triggerclick",[ms]),!0===cfg.expanded)ms.collapse();else{var e=ms.getRawValue().length;e>=cfg.minChars?(ms.input.focus(),ms.expand()):self._updateHelper(cfg.minCharsRenderer.call(this,cfg.minChars-e))}}};null!==element&&self._render(element)};$.fn.tagSuggest=function(e){var t=$(this);return 1===t.size()&&t.data("tagSuggest")?t.data("tagSuggest"):(t.each(function(t){var s=$(this);if(!s.data("tagSuggest")){"select"===this.nodeName.toLowerCase()&&(e.data=[],e.value=[],$.each(this.children,function(t,s){s.nodeName&&"option"===s.nodeName.toLowerCase()&&(e.data.push({id:s.value,name:s.text}),s.selected&&e.value.push(s.value))}));var n={};$.each(this.attributes,function(e,t){n[t.name]=t.value});var i=new TagSuggest(this,$.extend(e,n));s.data("tagSuggest",i),i.container.data("tagSuggest",i)}}),1===t.size()?t.data("tagSuggest"):t)}}(jQuery);


        $(document).ready(function() {
            var jsonData = [];
            var fruits = 'Apple,Orange,Banana,Strawberry'.split(',');
            for(var i=0;i<fruits.length;i++) jsonData.push({id:i,name:fruits[i]});
            var ms1 = $('#ms1').tagSuggest({
                data: jsonData,
                sortOrder: 'name',
                maxDropHeight: 200,
                name: 'ms1'
            });
        });

.tag-ctn{position:relative;height:28px;padding:0;margin-bottom:0;font-size:14px;line-height:20px;color:#555;-webkit-border-radius:3px;-moz-border-radius:3px;border-radius:3px;background-color:#fff;border:1px solid #ccc;-webkit-box-shadow:inset 0 1px 1px rgba(0,0,0,.075);-moz-box-shadow:inset 0 1px 1px rgba(0,0,0,.075);box-shadow:inset 0 1px 1px rgba(0,0,0,.075);-webkit-transition:border linear .2s,box-shadow linear .2s;-moz-transition:border linear .2s,box-shadow linear .2s;-o-transition:border linear .2s,box-shadow linear .2s;transition:border linear .2s,box-shadow linear .2s;cursor:default;display:block}.tag-ctn-invalid{border:1px solid #c00}.tag-ctn-readonly{cursor:pointer}.tag-ctn-disabled{cursor:not-allowed;background-color:#eee}.tag-ctn-bootstrap-focus,.tag-ctn-bootstrap-focus .tag-res-ctn{border-color:rgba(82,168,236,.8)!important;-webkit-box-shadow:inset 0 1px 1px rgba(0,0,0,.075),0 0 8px rgba(82,168,236,.6)!important;-moz-box-shadow:inset 0 1px 1px rgba(0,0,0,.075),0 0 8px rgba(82,168,236,.6)!important;box-shadow:inset 0 1px 1px rgba(0,0,0,.075),0 0 8px rgba(82,168,236,.6)!important;border-bottom-left-radius:0;border-bottom-right-radius:0}.tag-ctn input{border:0;box-shadow:none;-webkit-transition:none;outline:0;display:block;padding:4px 6px;line-height:normal;overflow:hidden;height:auto;border-radius:0;float:left;margin:2px 0 2px 2px}.tag-ctn-disabled input{cursor:not-allowed;background-color:#eee}.tag-ctn .tag-input-readonly{cursor:pointer}.tag-ctn .tag-empty-text{color:#ddd}.tag-ctn input:focus{border:0;box-shadow:none;-webkit-transition:none;background:#fff}.tag-ctn .tag-trigger{float:right;width:27px;height:100%;position:absolute;right:0;border-left:1px solid #ccc;background:#eee;cursor:pointer}.tag-ctn .tag-trigger .tag-trigger-ico{display:inline-block;width:0;height:0;vertical-align:top;border-top:4px solid gray;border-right:4px solid transparent;border-left:4px solid transparent;content:"";margin-left:9px;margin-top:13px}.tag-ctn .tag-trigger:hover{background:-moz-linear-gradient(100% 100% 90deg,#e3e3e3,#f1f1f1);background:-webkit-gradient(linear,0 0,0 100%,from(#f1f1f1),to(#e3e3e3))}.tag-ctn .tag-trigger:hover .tag-trigger-ico{background-position:0 -4px}.tag-ctn-disabled .tag-trigger{cursor:not-allowed;background-color:#eee}.tag-ctn-bootstrap-focus{border-bottom:1px solid #ccc}.tag-res-ctn{position:relative;background:#fff;overflow-y:auto;z-index:9999;-webkit-border-radius:3px;-moz-border-radius:3px;border-radius:3px;border:1px solid #ccc;left:-1px;-webkit-box-shadow:inset 0 1px 1px rgba(0,0,0,.075);-moz-box-shadow:inset 0 1px 1px rgba(0,0,0,.075);box-shadow:inset 0 1px 1px rgba(0,0,0,.075);-webkit-transition:border linear .2s,box-shadow linear .2s;-moz-transition:border linear .2s,box-shadow linear .2s;-o-transition:border linear .2s,box-shadow linear .2s;transition:border linear .2s,box-shadow linear .2s;border-top:0;border-top-left-radius:0;border-top-right-radius:0}.tag-res-ctn .tag-res-group{line-height:23px;text-align:left;padding:2px 5px;font-weight:700;border-bottom:1px dotted #ccc;border-top:1px solid #ccc;background:#f3edff;color:#333}.tag-res-ctn .tag-res-item{line-height:25px;text-align:left;padding:2px 5px;color:#666;cursor:pointer}.tag-res-ctn .tag-res-item-grouped{padding-left:15px}.tag-res-ctn .tag-res-odd{background:#f3f3f3}.tag-res-ctn .tag-res-item-active{background-color:#3875d7;background-image:-webkit-gradient(linear,0 0,0 100%,color-stop(20%,#3875d7),color-stop(90%,#2a62bc));background-image:-webkit-linear-gradient(top,#3875d7 20%,#2a62bc 90%);background-image:-moz-linear-gradient(top,#3875d7 20%,#2a62bc 90%);background-image:-o-linear-gradient(top,#3875d7 20%,#2a62bc 90%);background-image:linear-gradient(#3875d7 20%,#2a62bc 90%);color:#fff}.tag-sel-ctn{overflow:auto;line-height:22px;padding-right:27px}.tag-sel-ctn .tag-sel-item{background:#555;color:#eee;float:left;font-size:12px;padding:0 5px;border-radius:3px;margin-left:5px;margin-top:4px}.tag-sel-ctn .tag-sel-text{background:#fff;color:#666;padding-right:0;margin-left:0;font-size:14px;font-weight:400}.tag-res-ctn .tag-res-item em{font-style:normal;background:#565656;color:#fff}.tag-sel-ctn .tag-sel-item:hover{background:#565656}.tag-sel-ctn .tag-sel-text:hover{background:#fff}.tag-sel-ctn .tag-sel-item-active{border:1px solid red;background:#757575}.tag-ctn .tag-sel-ctn .tag-sel-item{margin-top:3px}.tag-stacked .tag-sel-item{float:inherit}.tag-sel-ctn .tag-sel-item .tag-close-btn{width:7px;cursor:pointer;height:7px;float:right;margin:8px 2px 0 10px;background-image:url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAcAAAAOCAYAAADjXQYbAAAACXBIWXMAAAsTAAALEwEAmpwYAAAKT2lDQ1BQaG90b3Nob3AgSUNDIHByb2ZpbGUAAHjanVNnVFPpFj333vRCS4iAlEtvUhUIIFJCi4AUkSYqIQkQSoghodkVUcERRUUEG8igiAOOjoCMFVEsDIoK2AfkIaKOg6OIisr74Xuja9a89+bN/rXXPues852zzwfACAyWSDNRNYAMqUIeEeCDx8TG4eQuQIEKJHAAEAizZCFz/SMBAPh+PDwrIsAHvgABeNMLCADATZvAMByH/w/qQplcAYCEAcB0kThLCIAUAEB6jkKmAEBGAYCdmCZTAKAEAGDLY2LjAFAtAGAnf+bTAICd+Jl7AQBblCEVAaCRACATZYhEAGg7AKzPVopFAFgwABRmS8Q5ANgtADBJV2ZIALC3AMDOEAuyAAgMADBRiIUpAAR7AGDIIyN4AISZABRG8lc88SuuEOcqAAB4mbI8uSQ5RYFbCC1xB1dXLh4ozkkXKxQ2YQJhmkAuwnmZGTKBNA/g88wAAKCRFRHgg/P9eM4Ors7ONo62Dl8t6r8G/yJiYuP+5c+rcEAAAOF0ftH+LC+zGoA7BoBt/qIl7gRoXgugdfeLZrIPQLUAoOnaV/Nw+H48PEWhkLnZ2eXk5N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ZWBqw8uIq2Km3VT6vtV5eufr0mek1rgV7ByoLBtQFr6wtVCuWFfevc1+1dT1gvWd+1YfqGnRs+FYmKrhTbF5cVf9go3HjlG4dvyr+Z3JS0qavEuWTPZtJm6ebeLZ5bDpaql+aXDm4N2dq0Dd9WtO319kXbL5fNKNu7g7ZDuaO/PLi8ZafJzs07P1SkVPRU+lQ27tLdtWHX+G7R7ht7vPY07NXbW7z3/T7JvttVAVVN1WbVZftJ+7P3P66Jqun4lvttXa1ObXHtxwPSA/0HIw6217nU1R3SPVRSj9Yr60cOxx++/p3vdy0NNg1VjZzG4iNwRHnk6fcJ3/ceDTradox7rOEH0x92HWcdL2pCmvKaRptTmvtbYlu6T8w+0dbq3nr8R9sfD5w0PFl5SvNUyWna6YLTk2fyz4ydlZ19fi753GDborZ752PO32oPb++6EHTh0kX/i+c7vDvOXPK4dPKy2+UTV7hXmq86X23qdOo8/pPTT8e7nLuarrlca7nuer21e2b36RueN87d9L158Rb/1tWeOT3dvfN6b/fF9/XfFt1+cif9zsu72Xcn7q28T7xf9EDtQdlD3YfVP1v+3Njv3H9qwHeg89HcR/cGhYPP/pH1jw9DBY+Zj8uGDYbrnjg+OTniP3L96fynQ89kzyaeF/6i/suuFxYvfvjV69fO0ZjRoZfyl5O/bXyl/erA6xmv28bCxh6+yXgzMV70VvvtwXfcdx3vo98PT+R8IH8o/2j5sfVT0Kf7kxmTk/8EA5jz/GMzLdsAAAAEZ0FNQQAAsY58+1GTAAAAIGNIUk0AAHolAACAgwAA+f8AAIDpAAB1MAAA6mAAADqYAAAXb5JfxUYAAABSSURBVHjahI7BCQAwCAOTzpThHMHh3Kl9CVos9XckFwQAuPtGuWTWwMwaczKzyHsqg6+5JqMJr28BABHRwmTWQFJjTmYWOU1L4tdck9GE17dnALGAS+kAR/u2AAAAAElFTkSuQmCC)}.tag-sel-ctn .tag-sel-item .tag-close-btn:hover{background-position:0 -7px}.tag-helper{color:#aaa;font-size:10px;position:absolute;top:-17px;right:0}

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<h3>Whats your favorite fruit</h3>
<input id="ms1" style="width:400px;" type="text" name="ms1"/>
<div style="clear:both;"></div>





由于CORS,请在您的环境中尝试此代码,在这里不起作用



<link href="https://phppot.com/demo/bootstrap-tags-input-with-autocomplete/bootstrap-tagsinput.css" rel="stylesheet"/>
<link href="https://phppot.com/demo/bootstrap-tags-input-with-autocomplete/typeahead.css" rel="stylesheet"/>
<script src="https://phppot.com/demo/bootstrap-tags-input-with-autocomplete/jquery-1.11.2.min.js"></script>
<script src="https://phppot.com/demo/bootstrap-tags-input-with-autocomplete/typeahead.js"></script>
<script src="https://phppot.com/demo/bootstrap-tags-input-with-autocomplete/bootstrap-tagsinput.js"></script>
<input type="text" value="" id="tags-input" data-role="tagsinput" />
<script>
  $(document).ready(function() {
    var countries = new Bloodhound({
      datumTokenizer: Bloodhound.tokenizers.obj.whitespace('name'),
      queryTokenizer: Bloodhound.tokenizers.whitespace,
      prefetch: {
        url: 'https://phppot.com/demo/bootstrap-tags-input-with-autocomplete/countries.json',
        filter: function(list) {
          return $.map(list, function(name) {
            return {
              name: name
            };
          });
        }
      }
    });
    countries.initialize();

    $('#tags-input').tagsinput({
      typeaheadjs: {
        name: 'countries',
        displayKey: 'name',
        valueKey: 'name',
        source: countries.ttAdapter()
      }
    });
  });
</script>

关于javascript - 我怎样才能使这个.autocomplete使其使用多个单词呢?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/58917262/

10-12 19:52