题解 | #设置标签#

设置标签

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();
}

全部评论

相关推荐

10-13 17:47
门头沟学院 Java
wulala.god:图一那个善我面过,老板网上找的题库面的
点赞 评论 收藏
分享
小红书 后端开发 总包n+8w+期权
点赞 评论 收藏
分享
评论
点赞
收藏
分享
牛客网
牛客企业服务