如何在 DOM 操作中结合 2 forEach vanilla JS

问题描述

我正在做一个练习,如果价格 > 3,00,我需要更改产品的背景颜色。 这是我到目前为止所做的。出于某种原因,如果我要更改价格颜色,它将完美运行,但是,当尝试更改 div backgroundColor 时,它会更改所有卡片。

我做错了什么?

这里是网站:[https://www.monoprix.fr/courses/legumes-frais-mpx_c0000400?page=22]

谢谢

function exercise_3() {
    var price = document.querySelectorAll(".grocery-item__normal-price");
    let changePriceColor = 300;
    var block = document.querySelectorAll(".grocery-item-item");


    block.forEach( item => {

        price.forEach(price => {

             var changeColor = price.innerHTML.slice(0,4).replace(/,/g,'');

             ( changeColor > changePriceColor ) ? 
             item.style.backgroundColor = "red" : ''; (not working)

             ( changeColor > changePriceColor ) ? 
             price.style.color = "red" : ''; (working)
        })
    
    })
}


var numberOfPriceElements = 0;

// count elements on load
numberOfPriceElements = document.querySelectorAll(".grocery-item__normal-price").length;

document.addEventListener('scroll',(e) => {
    // if count of elements is more then do the function and save the amount to the variable. 
    if(document.querySelectorAll(".grocery-item__normal-price").length > numberOfPriceElements) {
        exercise_3();
        numberOfPriceElements = document.querySelectorAll(".grocery-item__normal-price").length;
    }
});

exercise_3();

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)