有没有办法选择容器的CSSiID,该容器是由API的JS影响数据生成的



我正在构建一个页面,显示一些产品,数据来自API。该页面是用JS/es6和Bootstrap4构建的。到目前为止,我所做的是获取数据,并使用forEach动态生成带有API数据的产品卡。

示例:

listOfProducts.forEach(product => {
// We create a template a blueprint for our cards and passing with literal template
// Dynamically as foreach will loop and for every product in the array will print the card
// using ${product.title} we pass the title of the product from JSON OBJ of our products
// fetched from API
out += `<div class="col-sm-6 col-md-4 py-2">`;
out += `    <div id="${product.asin}" class="card h-100 d-flex flex-column">`;
// To img we give src of the img from JSON OBJ and ALT the ASIN
out += `        <img src="${product.img}" class="card-img-top" alt="${product.asin}">`;
out += `        <div class="card-body">`;
// We pass product title & price from JSON OBJ
out += `            <h5 class="card-title">${product.title}</h5>`;
out += `            <p class="card-text">${product.price}$</p>`;
// Button add to cart & skip
out += `            <button class="btn add-to-cart"><i class="fas fa-cart-plus"></i></button>`;
out += `            <button class="btn skip"><i class="far fa-trash-alt"></i></button>`;
out += `        </div>`;
out += `    </div>`;
out += `</div>`;
}); 

我的问题是当我开始在上面的例子中添加到购物车按钮时。我现在想实现的是,当我点击按钮时,卡片应该会选择将边框更改为绿色的类,但我无法获得所选的CSS id并将您选择的类附加或附加到它上。

我试过如下:

let test = row.querySelector('.add-to-cart').addEventListener('click', product => {
const productId = document.querySelector(`#${product.asin}`);
productId.class.add('selected');
});

但是控制台给了我一个错误,因为我的产品没有定义,或者如果我把它放在forEach中,我的产品id为null。

我正在努力找到最好的解决方案,因为我希望清楚如下:

  • 点击按钮添加到购物车
  • 点击后的产品会被选中,并且板的颜色会变为绿色

我的完整脚本在这里:mainjs

之所以会发生这种情况,是因为只有在事件触发时才会评估事件回调——此时,product.asin仅与迭代的最后一项相关,因为迭代已经完成。事实上,如果您将事件绑定到forEach之外,您将收到一个错误,因为product仅在forEach范围内本地定义,而不是在它之外。这将在控制台中引发错误。请始终检查错误控制台。

另一个问题是,您假设传递给事件回调的第一个参数是触发元素;它不是,它是一个事件对象。所以你需要它的.target属性:

在任何情况下,你都不需要关心ID来做你想做的事情。你只需要找到与点击的添加到卡按钮相关的容器元素。

还要注意,class.add应该是classList.add;这也会导致您的控制台出现错误。

最后,请记住,将事件侦听器的返回值(即undefined(分配给变量(在您的情况下为test(是没有意义的

因此:

row.querySelector('.add-to-cart').addEventListener('click', evt => {
evt.target.closest('.card').classList.add('selected');
});

最新更新