如果列表项存在,不要追加,而是更改字体颜色

If list item exists do not append but change the fontcolor

本文关键字:颜色 字体 列表 存在 如果 追加      更新时间:2023-09-26

我有这个脚本,如果列表项还没有准备好,它会追加一个列表项。我想要它做的是,如果列表项已经存在,它的字体颜色(css)设置为另一种颜色。

var itemName = userName,
    userFound = false;
$('#msgUserlist li').each(function () {
    if ($(this).text() === itemName) {
        userFound = true;
    }
});
if (userFound === true) {
    ////// at this point i want the fontcolor of the allready existing item be set.///
    return;
} else
    var newNode = document.createElement('li');
    newNode.innerHTML = '<a id="switchtoUser" name="' + userName + '" ' + 'onclick="ajaxChat.getHistory' + '(''' + userName + ''')"' + ' href="javascript:ajaxChat.sendPrivateMessageWrapper(''/query ' + userName + ''');">' + userName + '</a>';
    document.getElementById('msgUserlist').appendChild(newNode);
},

您可以在搜索用户时循环遍历列表:

// ...snip
$('#msgUserlist li').each(function () {
    if ($(this).text() === itemName) {
        userFound = true;
        $(this).css({
            color: "blue" // or whatever
        });
        return;
    }
});
// ...snip

你为什么不一找到就去做呢?

if ($(this).text() === itemName) {
    userFound = true;
    $(this).css('color', 'red'); // Example: change the color to red
}

我认为这将很好地解决Jquery函数css()

<ul id=msgUserlist>
    <li>Foo</li>
    <li>userName</li>
    <li>tball rulez</li>
</ul>
Javascript

var itemName = 'userName';
$( document ).ready(function() {
    $("#msgUserlist li").each(function() {
        if($(this).text() == itemName )
            $(this).css("color", "red");
    })
})

请参阅工作示例(简单,但可以使用您在问题中概述的逻辑进行扩展!):http://jsfiddle.net/PGfgv/601/