javascript - 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 创建的任何类。我究竟做错了什么?任何帮助是极大的赞赏
解决方案
您只是插入元素的文本内容,而不是元素本身,这就是为什么没有添加任何 DOM 的原因。此外,没有必要使用 insertAdjacentHTML ,因为newItem
它已经是一个Element,您可以使用appendChild()添加它。
代替
cartDropdown.insertAdjacentHTML('beforeend', newItem.textContent);
有类似的东西
cartDropdown.appendChild(newItem);
推荐阅读
- python - 如何检查元素是否在 Class.models.all() 中?
- python - django 重写序列化程序 save() 方法
- python - Python:计算相对于另一个图像不存在的非零像素的总数
- memory-management - 了解 64 位 Linux 上的 kmap
- nginx - 使用 Nginx 进行 301 重定向
- android - 在 android studio 中通过改造发送数据
- sql - 聚合单个 SQL 数据表
- node.js - 在电子中找不到自己构建的原生模块
- c++ - UE4 从外部 .FBX 文件创建 UStaticMesh 返回 NULL
- html - Css 左对齐元素