我有一个 SignalR 消息中心,它检查用户是否在线。
一旦我确定了连接用户的 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');
}
});
}
});
最佳答案
我不明白为什么你要使用更改事件,无论如何删除第一个 if 并使用像示例这样的选择器。 IF 不会像函数一样创建独立的作用域,因此您不能使用 $(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>
关于javascript - 检查 dom 元素是否具有数据属性 id,然后更新这些元素的数据属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36916023/