gpt4 book ai didi

javascript - 购物车只改变每场比赛第一个项目的颜色

转载 作者:行者123 更新时间:2023-12-04 07:18:53 26 4
gpt4 key购买 nike

我有这个功能可以添加到我的购物车 html 中,并且它工作正常。但是当我添加两个相同的项目时,我收到一个错误(只在每个相同项目的第一个更改颜色)。
console.log(changeBackgroundColor);控制台日志(更改颜色文本);只获取每场比赛的第一个 div。
enter image description here

   const addToCart = function () {
getJSON('games.json', function (err, data) {
var cartBets = document.getElementById('cart-bets');
if (err === null) {
console.log('Ocorreu um erro' + err);
} else {
let html = '';
regexPrice = data.types[whichLoteriaIsVar].price;
totalPrice += regexPrice;
let newTotalPrice = data.types[whichLoteriaIsVar].price
.toFixed(2)
.replace('.', ',');
html += '<div class="bar-side-cart">';
html += '<div class="side-by-side">';
html +=
'<div class="menu-thrash-save"><i onclick="deleteItemCart(this)" value="' +
data.types[whichLoteriaIsVar].price +
'" class="far fa-trash-alt" src="img/thrash-can.jfif" width=15 alt="Thrash"></i>
</div>';
html +=
'<div data-style="cart-thrash-side-bar-' +
data.types[whichLoteriaIsVar].type +
'" class="bets-backgroundcolor-lotos-container"></div>';
html += '<div class="top-by-top">';
html += '<p class="cart-right-text">' + totalNumbers + '</p>';
html += '<div class="side-by-side">';
html +=
'<div data-style="cart-text-thrash-' +
data.types[whichLoteriaIsVar].type +
'" class="bets-color-lotos-container">' +
data.types[whichLoteriaIsVar].type +
'</div>';
html += '<div class="cart-money">R$ ' + newTotalPrice + '</div>';
html += '</div>';
cartBets.innerHTML += html;
var changeBackgroundColor = document.querySelector(
'[data-style="cart-thrash-side-bar-' +
data.types[whichLoteriaIsVar].type +
'"]'
);
changeBackgroundColor.style.backgroundColor =
data.types[whichLoteriaIsVar].color;
var changeColorText = document.querySelector(
'[data-style="cart-text-thrash-' +
data.types[whichLoteriaIsVar].type +
'"]'
);
changeColorText.style.color = data.types[whichLoteriaIsVar].color;
console.log(changeBackgroundColor);
console.log(changeColorText);
getCartTotal();
}
});
};

最佳答案

document.querySelector()只返回第一个匹配的元素。尝试使用 document.querySelectorAll()带循环:

var changeBackgroundColor = document.querySelectorAll(
'[data-style="cart-thrash-side-bar-' +
data.types[whichLoteriaIsVar].type +
'"]'
);

changeBackgroundColor.forEach(
element => element.style.backgroundColor =
data.types[whichLoteriaIsVar].color
);

关于javascript - 购物车只改变每场比赛第一个项目的颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68625143/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com