【问题标题】:Dynamic JS channel menu link issue动态 JS 频道菜单链接问题
【发布时间】:2019-03-01 17:00:19
【问题描述】:

我正在开发一个聊天应用程序,用户可以在其中创建频道并在其中聊天。

每次单击侧面的频道链接(每次添加新频道时都会更新频道链接),我想将 localStorage 'channel' 变量(currentChannel)更新为单击链接的 id 并加载在右侧聊天窗口中使用 socket.on 调用服务器上的消息。但是,当我单击链接时没有任何反应。

我可能会补充一点,我的所有代码都在 document.addEventListener('DOMContentLoaded', () => { }) 中。尽管在 socket.on('update channels') 之后生成的带有 li 标记的链接正确显示在加载的页面上,但由于某种原因它们不会出现在源 HTML 中。任何帮助都非常感谢!

完整来源:https://github.com/kylepw/project2/blob/master/static/index.js

第 85 行的代码在初始化和添加新频道时更新频道链接。

// Update channel list
socket.on('update channels', channels => {
  if (channels) {
    channelsList = channels;
    channelsBar.innerHTML = ``;
    for (let channel of channelsList) {
      const li = document.createElement('li');
      li.innerHTML = `<a href="#" class="selectChannel" id="${channel}">${channel}</a>`;

      channelsBar.appendChild(li);
    }
  }
});

这(从第 155 行开始)是我试图对链接点击做出反应的地方:

const selectChannel = document.getElementsByClassName('selectChannel');
//...
// Load clicked channel 
for (let i = 0; i < selectChannel.length; i++) {
  selectChannel[i].addEventListener('onclick', () => {
    currentChannel = this.id;
    localStorage.setItem('channel', currentChannel);
    socket.on('messages', currentChannel); 
  });
}

【问题讨论】:

    标签: javascript socket.io chat


    【解决方案1】:

    我认为this.id 没有给您预期的结果。如果您检查页面上的 HTML 并且那里的频道 ID 是正确的,则尝试修改您的 onClick 函数以接受 e 参数并从中获取 ID:

    for (let i = 0; i < selectChannel.length; i++) {
         selectChannel[i].addEventListener('onclick', (e) => {
             let currentChannel= e.target.id; //id of the element you clicked
             localStorage.setItem('channel', currentChannel);
             socket.on('messages', currentChannel); 
         });
    }
    

    【讨论】:

    • 感谢您的评论,乔希。不幸的是,那没有用。另一个注意事项:可能是因为我正在使用 socket.on('update channels') 动态更新#channelsBar 中的频道,虽然链接显示在页面上,但 HTML 页面源并未显示它们。
    • 在您的socket.on('update channels') 中,您循环遍历频道并设置id="${channel}"。您是说当您查看 HTML 源代码时,您没有看到在每个 &lt;a&gt;id 字段中填充了正确的频道 ID?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-11-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-26
    • 1970-01-01
    相关资源
    最近更新 更多