Tag-it onlyAvalaibleTags选项不起作用

我使用https://github.com/aehlke/tag-it/downloads中的 tag-it插件。 如何禁用添加新标签?

$(document).ready(function () { $("#Tags").tagit({ singleField: true, singleFieldNode: $('#mySingleField'), // onlyAvailableTags : true, allowNewTags: false, tagSource: [@Html.Raw(ViewBag.AvailableTags)] }); }); 

我试图使用onlyAvailableTags : trueallowNewTags: false选项,但没有效果。

既然你说“但没有效果”,我猜想@Html.Raw(ViewBag.AvailableTags)产生的输出打破了javascript语法。 标签需要在引号中,否则它们被视为变量。

不正确的输出:

 tagSource: [my-tag, another-tag] 

服务器端,我假设你有某种IEnumerable

 ViewBag.AvailableTags = new List { "my-tag", "another-tag", }; 

然后,在你的.cshtml

 tagSource: ["@string.Join("\", \"", ViewBag.AvailableTags)"] 

这将产生正确的输出:

 tagSource: ["my-tag", "another-tag"] 

那将是我首先尝试的。

我发现通过评论:

  // Autocomplete will create its own tag from a selection and close automatically. if (!that.tagInput.data('autocomplete-open')) { that.createTag(that._cleanedInput()); } 

和:

 // Create a tag when the element loses focus. // If autocomplete is enabled and suggestion was clicked, don't add it. if (!that.tagInput.data('autocomplete-open')) { that.createTag(that._cleanedInput()); } 

它删除了此function。 也许不是最干净的方式,但它确实有效。

只需注释掉if(){ }循环。

这是我为tag-it的最新版本所做的:

 var tags_list = ['tag1', 'tag2, 'tag3]; $("input[name='subject-tags']").tagit({ availableTags : tags_list, beforeTagAdded : function(event, ui) { if(tags_list.indexOf(ui.tagLabel) == -1){ return false; } } }); 

试图通过实施使其更清洁

 $("input[name='subject-tags']").tagit({ availableTags : ['tag1', 'tag2, 'tag3], beforeTagAdded : function(event, ui) { if(this.availableTags.indexOf(ui.tagLabel) == -1){ return false; } } }); 

但是this.availableTags不返回数组(返回: undefined )。 我是一个JS菜鸟,所以我访问该属性的方式一定有问题。