【发布时间】:2017-04-23 23:42:33
【问题描述】:
我正在尝试使用 bootstrap-tagsinput 和 typeahead.js 为用户提供基于标签的输入机制,以选择一个或多个可用标签集合。这些标签匹配服务器端标志枚举中的可能值,服务器端模型绑定器喜欢在逗号分隔的列表中看到这些值(使一组标签完美)。
显示此内容的对话框将包含大量此类输入 - 每个都有不同的可用标签(通常每个四个或五个)。我想要做的是用一个属性填充每个输入,该属性包含一个逗号分隔的可能标记值列表,typeahead 可以从中读取。
这是一个适用于单个输入的 JavaScript 块示例:
$('#ExampleInput').tagsinput({
allowDuplicates: false,
freeInput: false,
typeaheadjs: [
{
hint: true,
highlight: true,
minLength: 0
}, {
source: function (query, syncResults) {
// an array that will be populated with substring matches
var matches = [];
// regex used to determine if a string contains the substring `q`
var substrRegex = new RegExp(query, 'i');
// iterate through the pool of strings and for any string that
// contains the substring `q`, add it to the `matches` array
$.each($('#ExampleInput').attr('data-values').split(','), function(i, str) {
if (substrRegex.test(str)) {
matches.push(str);
}
});
syncResults(matches);
}
}
]
});
这是输入的示例:(为了清楚起见,删除了一些不相关的数据验证)
<input class="form-control text-box single-line" data-values="Tag1,Tag2,Tag3,Tag4" id="ExampleInput" name="ExampleInput" type="text" value="Tag1, Tag2, Tag3, Tag4" />
如您所见,输入预输入位的源函数引用#ExampleInput 的 data-values 属性来拉取可用标签的列表。这一切都如我所愿。
我遇到的问题是,我希望能够针对一类输入大规模应用这种方法,而不是针对每个输入单独应用。我看不到如何让源函数知道目标输入对象(#ExampleInput),以便它可以跟踪特定于它为其提供源的输入的正确属性。
这可能吗?还是我必须将每个输入与其自己的静态预输入源配对?
【问题讨论】:
标签: javascript jquery typeahead.js bootstrap-tags-input