简体   繁体   中英

(Socket.IO) how to add class to current user's username in userlist?

Basically I'm working on a chat room application and I'm using forEach to list all of the users in the room, how would I add a class to only the current user's username?

Code

socket.on('updateUserList', function(users) {
  var ul = $('<ul class="ul-unstyled"></ul>');

  users.forEach(function(user) {
    ul.append($('<li class="userlist__item"></li>').text(user));

    if(users.length <= 1) {
      $('#counter').text(users.length + " Member");
    } else {
      $('#counter').text(users.length + " Members");
    }
  });
  $('#users').html(ul);
});

Thanks.

You must have a id or a unique identifier to the current username (eg id)

    var id = myid; //(e.g. current user id)
    socket.on('updateUserList', function(users) {
      var ul = $('<ul class="ul-unstyled"></ul>');

      users.forEach(function(user) {
        //If current user is equal to current id
        if(user.id == id){
         ul.append($('<li class="userlist__item YOUR_CURRENT_USERNAME CLASS"></li>').text(user));
        } else {
         ul.append($('<li class="userlist__item"></li>').text(user));
        }
        if(users.length <= 1) {
          $('#counter').text(users.length + " Member");
        } else {
          $('#counter').text(users.length + " Members");
        }
      });
      $('#users').html(ul);
    });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM