简体   繁体   English

jQuery addClass覆盖上一个元素

[英]jQuery addClass overrides previous element

$('#naiveComments').append("<ul id='newList'></ul>").css("color", "white");
var keys = Object.keys(result);

for (var i = 0; i < keys.length; i++) {
    var key = keys[i];
    console.log(result[key]);

    if (result[key] == 1)
    {
        $("#newList").append("<li>" + key + "</li>").addClass("positive");
    }
    else if (result[key] == -1)
    {
        $("#newList").append("<li>" + key + "</li>").addClass("negative");
    }
}

My result[key] field stores a value of 1,0 and -1. 我的result[key]字段存储的值为1,0和-1。 Based on this value I would like to add a specific class to the current <li> </li> element, however the last addClass will be the final one. 基于此值,我想向当前<li> </li>元素中添加特定的类,但是最后一个addClass将是最后一个。 I'm aware of the fact that in my case this sets the class for every <li> element but I'm unable to find a way in which I could set different classes to different <li> elements. 我知道以下事实:在我的情况下,这会为每个<li>元素设置类,但是我无法找到一种方法可以为不同的<li>元素设置不同的类。

You want appendTo , not append : 您想要appendTo ,而不是append

This adds a class to #newList : 这会向#newList添加一个类:

$("#newList").append("<li>" + key + "</li>").addClass("positive");

This adds a class to a new li in #newList : 这将类添加到#newList的新li中:

$("<li>" + key + "</li>").appendTo("#newList").addClass("positive");

The result of .append() is the element you're appending to (so you can chain multiple appends), not the element you added. .append()的结果是您要追加的元素(因此您可以链接多个追加),而不是您添加的元素。 You need to create the new element as the argument, and add the class to that. 您需要创建新元素作为参数,并在其中添加类。

$("#newlist").append(
    $("<li>", {
        text: key,
        "class": "positive"
    })
);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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