题解 | #购物车#
设置标签
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 span=document.createElement('span')
span.classList.add('tag')
span.innerText=input.value.trim()
var tags=document.querySelectorAll('.tag')
var test=[]
tags.forEach((item)=>{
test.push(item.innerText)
})
if(test.indexOf(span.innerText)==-1){
if(span.innerText==''){
input.value=''
return ;
}else{
input.parentNode.insertBefore(span,input)
}
}
input.value=''
}
function removeTag() {
var that=this
var input=that.input
if(!input.value.trim()){
var parent=input.parentNode
if(parent.children.length>1){
parent.removeChild(parent.children[parent.children.length-2])
}
}else{
input.value=input.value.slice(0,-1)
}
}