2016-04-28 53 views
1

我有一个SignalR messagingHub,它检查用户是否在线。检查具有数据属性id的dom元素然后更新这些元素数据属性

一旦我确定了连接用户的ID和状态,那么我需要更新任何包含具有用户ID的数据属性的dom元素并更新其状态。

基本上,我需要在网站上显示每个dom元素的不同类,以显示哪个用户在线,哪个不在。

这是我初步的尝试:

chatMessagingHub.on('updateUserOnlineStatus', function (userId, isOnline) { 

    var status = (isOnline) ? 'online' : 'offline'; 

    console.log('userid: ' + userId + ' status: ' + status); 

    // Check the user id matches any dom elements with a data-attr userid 
    if($('[data-userId]') == userId) { 

     // Update the selected dom elements data-status attributes 
     $(this).attr('[data-status]', isOnline); 

     // Detect the change and update the class of the dom element 
     $(this).on('change', function() { 

     // Check the value of the data-status parameter to add class 
     if($(this).attr('data-status') == 'offline') { 

      $(this).removeClass('online'); 

     } else { 

      $(this).addClass('online'); 

     } 
     }); 
    } 
}); 
+0

只需加$(本).trigger(“变”); – Thorin

+0

是$(this)是指chatMessagingHub? – Vanojx1

+0

我想将$(this)作为具有匹配attr用户标识的dom元素 –

回答

0

我无法弄清楚,为什么你正在使用的change事件,反正删除第一个,如果和使用选择类似的例子。中频不创建一个孤立的范围像一个函数,所以你不能使用$(this)作为选择的DOM元素

$(function() { 
 
    var isOnline = true; 
 
    var userid = 1; 
 
    var status = (isOnline) ? 'online' : 'offline'; 
 
    var elem = $("[data-userid=" + userid + "]"); 
 
    elem.attr("data-status", isOnline); 
 
    if (status === "offline") 
 
    elem.removeClass("online") 
 
    else 
 
    elem.addClass("online"); 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<span data-userid="1">hello!</span> 
 
<span data-userid="2">hello!</span> 
 
<span data-userid="1">hello!</span> 
 
<span data-userid="4">hello!</span>

+0

将尝试此解决方案,干杯 –