Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
469 views
in Technique[技术] by (71.8m points)

javascript - 如何将onclick事件添加到动态生成的HTML元素(How to add onclick event to dynamically generated HTML elements)

Im trying to develop a chat app that allows for users to create a new chat room.

(我正在尝试开发一个聊天应用程序,以允许用户创建一个新的聊天室。)

I already have code that runs for each item in the list, on click, will add users to the new room

(我已经有针对列表中每个项目运行的代码,单击后会将用户添加到新房间)

Javascript:

(Javascript:)

document.querySelectorAll('.select-room').forEach(li => {
    li.onclick = () => {
        let newroom = li.innerHTML;
        if (newroom == room){
            msg = `You are already in ${room} room.`
            printSysMsg(msg);
        } else {
            leaveRoom(room);
            joinRoom(newroom);
            room = newroom;
        }
    }
});

HTML:

(HTML:)

            <nav id='sidebar'>
            <h4>ROOMS</h4>
            <ul id='room_list' >
                {% for room in rooms %}
                    <li class = 'select-room'>{{ room }}</li>
                {% endfor %}
            </ul>                
        </nav>

However, when i add new rooms, im not able to click on the list item straight away to change chat rooms, i would have to refresh the page.

(但是,当我添加新房间时,我无法立即单击列表项来更改聊天室,因此我必须刷新页面。)

Any help would be greatly appreciated

(任何帮助将不胜感激)

  ask by Bryan Choo translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Have you tried adding an event listener?

(您是否尝试添加事件监听器?)

So in your forEach:

(因此,在您的forEach中:)

 document.querySelectorAll('.select-room').forEach(li => { li.addEventListener('click', () => { let newroom = li.innerHTML; if (newroom == room){ msg = `You are already in ${room} room.` printSysMsg(msg); } else { leaveRoom(room); joinRoom(newroom); room = newroom; } }) }); 


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...