题解 | #设置标签#
设置标签
http://www.nowcoder.com/practice/b164e87713804e1ab46cf7a84936b6ba
var tagInput = {
isInited: false,
init: init,
bindEvent: bindEvent,
addTag: addTag,
removeTag: removeTag
};
tagInput.init();
function init() {
var that = this;
if (that.isInited) return;
that.isInited = true;
// 请修改这一行代码,保存class为js-input的输入框的dom元素引用
that.input = document.querySelector('.js-input');
that.bindEvent();
}
function bindEvent() {
var that = this;
var input = that.input;
if (!input) return;
input.addEventListener('keydown', function (event) {
// 请修改这一行代码,判断用户是否按了回车键
var isEnter = event.keyCode === 13;
// 请修改这一行代码,判断用户是否按了删除键
var isDelete = event.keyCode === 8;
(isEnter || isDelete) && event.preventDefault();
isEnter && that.addTag();
isDelete && that.removeTag();
});
input.parentNode.addEventListener('click', function () {
input.focus();
});
}
function addTag() {
var that = this;
var input = that.input;
var tagInput = document.querySelector('.tag-input');
//已有的标签组成数组
var tags = Array.from(tagInput.querySelectorAll('span')).map(i => i.innerHTML);
var value = input.value.trim(); //去两端空格
//如果为空字符串 或者 已有标签 清空内容
if(value === "" || tags.includes(value)){
input.value = "";
return ;
} else {
//新建span节点插入输入框前
var newTag = document.createElement('span');
newTag.className = "tag";
newTag.innerHTML = value;
tagInput.insertBefore(newTag, input);
input.value = "";
}
}
function removeTag() {
var that = this;
var input = that.input;
var tagInput = document.querySelector('.tag-input');
//输入框中还有内容,实现普通的字符串删除
if(input.value.length > 0){
input.value = input.value.substr(0, input.value.length - 1);
}
else {
//输入框中无内容 删除最后一个标签
try {
var delTag = Array.from(tagInput.querySelectorAll('span')).pop();
tagInput.removeChild(delTag);
}
catch(err) {//防止标签已经全部删除后的报错}
}
}