首页 > 解决方案 > Javascript 读取一次然后部分忽略?

问题描述

以下 JS 在我的 HTML 下的脚本标记中。当页面最初加载时,该文件似乎可以工作。创建了一个通道,当我单击它时,console.log 语句会出现,表明它是可操作的。然后我成功添加了一个频道。但是,当我单击附加频道时,什么也没有发生。我从来没有到达页面底部的.forEachclickeventListener —— 一个专门为多通道按钮构建的案例。我尝试了各种配置并研究了查询选择器和 forEach。我哪里错了?

(function() {


    //connect to websocket: copy must be inside request.onload for chat room to register user entry
    let socket = io.connect(location.protocol + '//' + document.domain + ':' + location.port);

    if (socket) 
        console.log("Socket connected!");

    socket.on('connect', () => {
        // track number of channels and channel names
        let channelCount = 1;
        let channelList = ["Lobby"];

        // create & display new channels added by user
        let createChannelBtn = document.querySelector('#chanlBtn');

        createChannelBtn.addEventListener('click', function(e) {

            //e.preventDefault();

            let newChannel = document.querySelector('#chanl').value;

            // add a channel if not a duplicate
            if (channelList.indexOf(newChannel) > -1) {

                document.querySelector('#chanl').value = '';

            } else {
                channelCount += 1;
                channelList.push(newChannel);

                console.log(channelList);
                console.log(channelCount);
                let textnode = document.createTextNode(newChannel);
                let node = document.createElement('button');
                node.className += 'dropdown-item';
                node.setAttribute('type', 'button');
                node.setAttribute('id', 'selectChannel');
                node.setAttribute('data-channel-', 'newChannel');
                node.appendChild(textnode);
                document.querySelector('#chanlMenu').appendChild(node);
                document.querySelector('#chanl').value = '';

            }

        });

        if (channelCount == 1) {
            var channel_button = document.querySelector('#selectChannel');
            console.log("channel 1 =" + channel_buttons);
            console.log("channelCount 1 =" + channelCount);
            channel_button.addEventListener('click', function() {
                let room = channel_button.dataset.channel;
                console.log("Inside lobby");
                socket.emit('join', {'username':localStorage.getItem('login'), 'room':room});
            });
        } 

        var channel_buttons = document.querySelectorAll('#selectChannel');


    HERE'S THE SECTION I NEVER REACH AFTER A CHANNEL BUTTON IS ADDED
            channel_buttons.forEach( channel_button => {
                channel_button.addEventListener('click', function() {
                let room = channel_button.dataset.channel;
                console.log("Sending 1 Button signal from Node List");
                //socket.emit('join', {'username':localStorage.getItem('login'), 'room':room});
            });

        });

    });

})()

标签: javascript

解决方案


看起来您在页面加载时将点击处理程序添加到通道按钮。

这个问题是按钮还不存在,所以你正在循环一个由创建的空列表var channel_buttons = document.querySelectorAll('#selectChannel');

(尝试在该行之后放置一个console.log(channel_buttons);以查看列表包含的内容)

您需要在创建节点之后将事件侦听器添加到节点(可能类似于node.addEventListener(...)在您的node.appendChild(textnode);行之后,或者使用事件委托在父节点上放置一个单击处理程序,该处理程序将处理所有新按钮的单击。


推荐阅读