簡體   English   中英

jQuery .css()不更新元素

[英]jQuery .css() does not update element

function createList() {
var list = '';
var listID;
$.each(obj_JSON.colors, function(index, value) {
    listID = "clr_" + index;
    list = list + "<div id=" + listID + " alt='" + obj_JSON.colors[index].name + "'></div>"
    clrList.html(list);
    updateListColours(listID);
});

}

function updateListColours(x) {
    $('#' + x).css({"background-color":"rgb(255, 0, 0)", "height":"25px", "width":"25px"});
}

當我看着它被創建時。 第一個div會應用樣式。 然后創建第二個,然后從第一個div擦除樣式並將其應用於第二個div,直到列表完成。

為什么會發生這種情況,如何將樣式應用於每個div? 期望得到的答案表明我像往常一樣做得非常愚蠢

因為這一行clrList.html(list); ,您將刪除上一個元素,然后添加新創建的元素。

相反,請執行以下操作:

$.each(obj_JSON.colors, function(index, value) {
    listID = "clr_" + index;
    list = "<div id=" + listID + " alt='" + obj_JSON.colors[index].name + "'></div>"
    clrList.append(list);
    updateListColours(listID);
});

有一個更簡單的解決方案:

function createList() {
    $.each(obj_JSON.colors, function() {
        var d = document.createElement('div');
        d.setAttribute("alt",this.name);
        d.className = "listcolour";
        clrList.appendChild(d);
        // ^ assumes `clrList` is a DOM node, not a jQuery object
    });
}

和CSS:

.listcolour {
    width: 25px;
    height: 25px;
    background-color: #f00;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM