首页 > 解决方案 > CSS 不会影响使用 JavaScript 生成的任何 HTML。我究竟做错了什么?

问题描述

我正在尝试通过 javascript 制作一个 javascript 购物车 HTML。单击一个项目时,它会将其添加到购物车中。尝试修改 javascript 生成的 HTML 时,CSS 不会保留。怎么了?

//dropdown menu hidden
const cartDropdown = document.querySelector('.cart-dropDown-items');

//every single + symbol
const addToCartButtons = document.querySelectorAll('.addToCart');

//price of item
const foodPrices = document.querySelectorAll('.selection-row-title');

//name of item
const foodNames = document.querySelectorAll('.selection-row-foodName');

//weight of item
const foodWeights = document.querySelectorAll('.selection-row-weight');

for (let i=0; i<addToCartButtons.length; i++) {
    addToCartButtons[i].addEventListener('click', function() {
        const newItem = document.createElement('div');
        newItem.className = 'dropDown-item'
        newItem.innerHTML = `
                            <div class='dropDown-title dropDown-info'>
                                ${foodNames[i].textContent}
                            </div>
                            <div class='dropDown-amount dropDown-info'>
                                ${1}
                            </div>
                            <div class='dropDown-price dropDown-info'>
                                ${foodPrices[i].textContent}
                            </div>`;


        console.log(newItem)
        // if item currently exists in array, just update amount in checkout and increase count++
        if (items.includes(addToCartButtons[i].value)) {
        // if items does not exist in array, update dom with new item UI and count = 1 by default
        } else {
            items.push(addToCartButtons[i].value);
            cartDropdown.insertAdjacentHTML('beforeend', newItem.textContent);
        }
    })
}

                <div class='cart-dropDown'>
                    <div class='cart-dropDown-header'>
                        <p>My Carts</p>
                        <p>Personal Cart</p>
                        <p class='cart-dropDown-close'>Close</p>
                    </div>
                    <p class='cart-dropDown-empty'></p>
                    <div class='cart-dropDown-items'>
                        
                    </div>
                </div>
    //newItem DOM
.cart-dropDown-items {
    display:flex;
    flex-direction: row;
}

.dropDown-title {

}

.dropDown-item {
    display: flex;
    flex-direction: row;
    padding: 10px;
    background-color:red ;
    color:red;
}

CSS 不会影响使用 createElement、innerHTML 创建的任何类。我究竟做错了什么?任何帮助是极大的赞赏

标签: javascripthtmlcss

解决方案


您只是插入元素的文本内容,而不是元素本身,这就是为什么没有添加任何 DOM 的原因。此外,没有必要使用 insertAdjacentHTML ,因为newItem它已经是一个Element,您可以使用appendChild()添加它。

代替

cartDropdown.insertAdjacentHTML('beforeend', newItem.textContent);

有类似的东西

cartDropdown.appendChild(newItem);

推荐阅读