题解 | #设置标签#
设置标签
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.getElementsByClassName('js-input')[0];
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 tags = document.getElementsByClassName('tag');
var curInput = input.value.trim()
var allTagName = [];
[].forEach.call(tags, item=>{
allTagName.push(item.innerText.trim());
});
if (!curInput || allTagName.indexOf(curInput) !== -1) {
input.value = ''
return
}
var el = document.createElement('span');
el.classList.add("tag");
el.innerText = input.value.trim()
input.parentNode.insertBefore(el, input)
input.value = ''
}
function removeTag() {
var that = this;
var input = that.input;
if (input.value.trim() == '') {
var tags = document.querySelectorAll('.tag')
if(tags.length > 0 ){
tags[tags.length-1].remove()
}
}
}