「这是我参与2022首次更文挑战的第14天,活动详情查看:2022首次更文挑战」
1、问题引入
这篇分享是上次开发的一个发布文章的功能时遇到的一个问题,要将多个不同的标签选中,放入标签框。效果如下:
完成这个功能还是废了一点力的,刚开始打算使用select2,但是在自定义标签框里需要用户自己输入。尝试了很多次,如果使用select2的话有很大的改造,然而迫于工期紧张,笔者平常主写后端,JS什么的不是很精通。百度了很多也是不太符合要求,只能都参照了些,自己改了改。那么下面就为大家具体分享下。
2、实现代码
//1、首先是多标签显示栏与固定标签选择框与自定义标签栏
<div class="tag-container" >
<input type="text" class="tag-input" autocomplete="off" placeholder="添加标签" disabled>
</div>
<label class="layui-form-label" >固定标签</label>
<div class="layui-input-inline">
<div class="layui-unselect layui-form-select downpanel" >
<div class="layui-select-title" >
<span class="layui-input layui-unselect" >请选择标签</span>
<input type="hidden" name="fixed_tag" lay-filter="couponType" />
<i class="layui-edge"></i>
</div>
<dl class="layui-anim layui-anim-upbit">
<dd>
<ul id="comTagsTree"></ul>
</dd>
</dl>
</div>
</div>
<div class="layui-form-item">
<button type="button" class="layui-btn layui-btn-radius" id="addCustomTag">确定</button>
<label class="layui-form-label">自定义标签</label>
<div class="layui-input-inline">
<input type="text" name="custom_tag" placeholder="在此输入标签关键词" class="layui-input" />
</div>
</div>
然后,最重要的就是如何处理标签的添加及删除事件,这里为大家分享下关键代码:
//初始化函数
init(options) {
var spans = '';
this.options = $.extend(this.options, options);
$.each(this.options.data, function (index, item) {
spans += this.spanHtml(item);
});
this.elem.before(spans);
}
//定义监听函数、监听标签的删除
listen() {
var that = this;
this.elem.parent().on('click', 'a', function () {
that.removeItem($(this).parent('span'));
});
this.elem.parent().on('click', function () {
that.elem.focus();
});
this.onChange();
}
createItem() {
var value = this.elem.val().trim();
this.createItemVal(value);
}
//将某一个标签加入到显示栏
createItemVal(value) {
if (!value) return false;
if (!this.options.data.includes(value)) {
this.options.data.push(value);
this.elem.before(this.spanHtml(value));
}else {
alert(`当前标签[${value}]已存在!`);
}
this.elem.val('');
this.onChange();
}
//移除某个标签
removeItem(target) {
var that = this;
var closeSpan = target.remove(),
closeSpanText = $(closeSpan).children('span').text();
that.options.data.splice($.inArray(closeSpanText, that.options.data), 1);
that.onChange();
}
//标签发生改变时的回调函数,作为参数传入
onChange() {
this.options.onChange && typeof this.options.onChange === 'function' && this.options.onChange(this.options.data);
}
好了、本期就先介绍到这里,有什么需要交流的,大家可以随时私信我。😊