2016-04-28 52 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

將嘗試此解決方案,乾杯 –