如何实现单聊天室打开功能?移除room-前缀ID元素的正确方法
Hey there! I see you're trying to adjust your chat app so only one room is open at a time, and you ran into trouble with removing existing rooms. Let's get this sorted out.
The Problem with Your Current Approach
Your attempt $("#room-" + * ).remove(roomdiv); doesn't work because jQuery doesn't support that wildcard syntax directly. The selector is invalid, so no elements get targeted for removal.
Two Simple Solutions
We have two straightforward ways to remove all open chat rooms before adding a new one:
1. Use the Room Class Selector (Recommended)
Since every chat room div has the room class, we can target all of them directly with this class selector. This is clean and easy to maintain:
// Remove all existing room containers $(".room").remove();
2. Use an ID Prefix Attribute Selector
If you prefer targeting by the ID prefix (room-), jQuery supports attribute selectors where we match elements whose ID starts with a specific string:
// Remove all elements with IDs starting with "room-" $("[id^='room-']").remove();
Updated Full Code
Just add the removal line before you append the new room div. Here's the fixed code:
if (data.join) { console.log("Joining room " + data.join); // Remove all existing chat rooms first $(".room").remove(); // Alternative: $("[id^='room-']").remove(); var roomdiv = $( "<div class='room' id='room-" + data.join + "'>" + "<h2>" + data.title + "</h2>" + "<div class='messages'></div>" + "<input><button>Send</button>" + "</div>" ); $("#chats").append(roomdiv); }
Bonus: Cleanup Before Removal (If Needed)
If your chat rooms have event listeners or other state you need to clean up first, you can loop through the rooms before removing them:
$(".room").each(function() { // Example: Unbind send button events $(this).find("button").off("click"); // Add any other cleanup logic here }).remove();
This ensures only one chat room is ever visible at a time—when you join a new room, all old ones get cleared out first.
内容的提问来源于stack exchange,提问作者Jay Jung

