簡體   English   中英

如何使用jQuery將類名添加到對象屬性的數組列表中?

[英]How to add class name to an array list of an object property using jQuery?

我試圖讓每一個類名td ,然后添加其他類各td 例如:當前類是class = "X-marker" ,我想添加另一個類bgreen ,它應該是class = "X-marker bgreen"

我使用了each方法來獲取每個td的類名,然后將attr與每個方法一起使用來設置,但它不起作用。 我沒有收到任何錯誤,但是沒有按預期工作。

該對象稱為winInfo ,數組變量為: winInfo.play = winArray[i];

var winInfo = checkWin();
if (winInfo.win) {
    currentClass = $(winInfo.play).each(function () {
        $(this).attr('class');
    });

    $(winInfo.play).each(function () {
        $(this).attr('class', currentClass + ' bgreen');
    });
}

聽起來您正在尋找addClass()

可能看起來像這樣:

$(winInfo.play).addClass('bgreen');

如@Hatchet所述,方法addClass顯然是最簡單的方法。 但是,由於您似乎誤解了each函數的工作原理,因此這是您可以在不使用addClass情況下使用each

在下面,我假設winInfo.play是一個適當的dom選擇器(例如".class-name p" )。

var winInfo = checkWin();
if (winInfo.win) {
    // `each` is just a helper that will call the provided function
    // for each of the object selected by jQuery (like a loop).
    // It does not return any value.
    $(winInfo.play).each(function () {
        var currentClass = $(this).attr('class');
        $(this).attr('class', currentClass + ' bgreen');
    });
}

哦,因為您可能不需要jQuery ,所以這是在普通js中的操作方式。

var winInfo = checkWin();
if (winInfo.win) {
  // if winInfo.play is not a selector but a list of dom elements,
  // just remove document.querySelectorAll.
  for(var el of document.querySelectorAll(winInfo.play)){
    el.classList.add('bggreen');
  }
}

暫無
暫無

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

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