如何解决Select2 标记:在新标记后面添加自定义文本
我正在使用 select2 tagging feature。有没有一种简单的方法可以在新标签后面添加自定义文本。我的意图是,用户知道他/她会添加标签。
结果应该看起来像这样,例如。以颜色名称为例,它可以在新标签后说“新颜色”:
$(".js-example-tags").select2({
tags: true
});
select,pre {
display: inline-block;
}
.js-example-tags {
width: 256px;
}
<link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script>
<select class="js-example-tags">
<option selected="selected">orange</option>
<option>white</option>
<option>purple</option>
</select> <pre><== Type new tag into search and click enter</pre>
解决方法
如果我理解你的逻辑,你可以试试这个:
$(".js-example-tags").select2({
tags: true,createTag:newtag,matcher: matchCustom,});
function newtag(params,data){
var term = $.trim(params.term);
if (term === '') {
return null;
}
return {
id: term,text: term + " (New color)",newTag: true // add additional parameters
}
}
function matchCustom(params,data) {
// If there are no search terms,return all of the data
if ($.trim(params.term) === '') {
return data;
}
// Do not display the item if there is no 'text' property
if (typeof data.text === 'undefined') {
return null;
}
// Return `null` if the term should not be displayed
return null;
}
select,pre {
display: inline-block;
}
.js-example-tags {
width: 256px;
}
<link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script>
<select class="js-example-tags">
<option selected="selected">orange</option>
<option>white</option>
<option>purple</option>
</select> <pre><== Type new tag into search and click enter</pre>
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。