![](/img/trans.png)
[英]How to add an object property inside an array using a variable name for javascript?
[英]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');
});
}
如@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.