题解 | #设置标签#
设置标签
https://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 text = input.value.trim(); if (!text) return; var newTag = document.createElement("span"); newTag.className = "tag"; newTag.innerHTML = text; document.querySelector(".tag-input").insertBefore(newTag, input); input.value = ""; } function removeTag() { var that = this; var input = that.input; var text = input.value; if (text) return; var tags = document.querySelectorAll(".tag-input .tag"); if (tags.length <= 0) return; tags[tags.length - 1].remove(); }