我使用 typeahead.js 和 jquery 创建了一个小提琴。请看一看。
https://jsfiddle.net/Rohith_KP/k73msa47/
! function(source) {
function extractor(query) {
var result = /([^,]+)$/.exec(query);
if (result && result[1])
return result[1].trim();
return '';
}
function tagTmpl(item) {
return '<div class="selected">' +
'<span class="value-wrapper">' +
'<div class="value">' + item + '</div>' +
'<div class="value-close"></div>' +
'</span>' +
'</div>'
}
<!--init -->
var initData = ["Alabama", "Alaska", "Arizona", "Arkansas"],
tagTmpls = '';
$.each(initData, function(index, item) {
tagTmpls += tagTmpl(item);
})
$('.multiselect').before(tagTmpls);
$('.multiselect-display').text(initData.join(', '));
$('.multiselect').data({
"selectedValues": initData
});
<!-- end init -->
$('.multiselect').typeahead({
source: source,
updater: function(item) {
var tmpl = tagTmpl(item);
this.$element.before(tmpl);
var dataToSend = this.$element.data("selectedValues");
dataToSend = dataToSend ? dataToSend : [];
dataToSend.push(item);
this.$element.data({
"selectedValues": dataToSend
})
return '';
},
matcher: function(item) {
var tquery = extractor(this.query);
if (!tquery) return false;
return ~item.toLowerCase().indexOf(tquery)
},
highlighter: function(item) {
var query = extractor(this.query).replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g, '\\$&')
return item.replace(new RegExp('(' + query + ')', 'ig'), function($1, match) {
return '<strong>' + match + '</strong>'
})
}
});
$('.multiselect-wrapper').off('click').on('click', '.value-close', function() {
$this = $(this);
var text = $this.siblings('.value').text();
var selectedValues = $(event.currentTarget).find('.multiselect').data("selectedValues");
removeStringFromArray(selectedValues, text);
$this.parents('.selected').hide();
window.setTimeout(function() {
$this.parents('.selected').remove();
}, 0)
})
$('.multiselect-wrapper').off('click', multislctWrprClickHndlr).on('click', multislctWrprClickHndlr)
function multislctWrprClickHndlr(e) {
$("body").off('click', bodyClickHandler).on('click', bodyClickHandler);
if (!$(e.target).is('.selected')) {
$('.multiselect').focus()
}
};
$('.multiselect-display').off('click', multislctDsplyClickHndlr).on('click', multislctDsplyClickHndlr)
function multislctDsplyClickHndlr() {
$(this).hide()
$('.multiselect-wrapper').trigger('click').show();
};
function bodyClickHandler(e) {
debugger;
if ($(e.target).is('.multiselect-wrapper') || $(e.target).parents('.multiselect-wrapper').length || $(e.target).is('.multiselect-display') || $(e.target).parents('.multiselect-display').length) {
e.preventDefault();
return;
}
$("body").off('click', bodyClickHandler);
$('.multiselect-wrapper').hide();
$('.multiselect-display').text($('.multiselect').data("selectedValues").join(', ')).show()
}
function removeStringFromArray(array, search_term) {
for (var i = array.length - 1; i >= 0; i--) {
if (array[i] === search_term) {
array.splice(i, 1);
break;
}
}
}
}(["Alabama", "Alaska", "Arizona", "Arkansas", "California", "Colorado", "Connecticut"]);