我正在使用无法控制HTML的电子商务页面。我正在尝试为每个列表项(样本)添加价格。
// This is some hidden HTML being displayed on the page that has altered prices in it.
const superAttributesRaw = [...document.querySelectorAll('.super-attribute-select option')];
const superAttributes = superAttributesRaw.filter(newValue => Object.keys(newValue).length !== 0);
// This is the shown HTML swatch I need to add the altered prices to.
const swatchUl = [...document.querySelectorAll('.swatchesContainer ul li')];
// Pulling out the altered prices and putting them into an array.
prices = [];
for (let value of superAttributes) {
prices.push(value.config.price);
}
// This adds the sample text where I need it in the unordered list of swatches. I just need 'test' to be the altered prices.
for (let value of swatchUl) {
value.insertAdjacentHTML('beforeend', '<span>' + 'test' + '</span>');
}
我的价格数组如下:
prices = ["0","0","0","0","0","0","0","0","0","0","0","0","0","0","0","0","0","0","0","0","0","0","0","0","0","0","0","0","0","0","0","0","0","0","-2","0","0","0","0","0","0","0"]
“测试”在第二个for循环中,我需要它以某种方式显示价格。我不确定如何遍历价格循环中的每个项目并以正确的顺序显示第一,第二,第三等。
我尝试嵌套for循环,结果变得一团糟。如果不是很明显,我的术语会很糟糕,因此我很难完全按照自己的需要进行搜索。任何帮助表示赞赏。谢谢!
答案 0 :(得分:5)
如果可以保证swatchUl数组中的索引与您的价格数组中的价格相对应,则可以执行以下操作:
swatchUl.forEach((swatch, index) => {
swatch.insertAdjacentHTML('beforeend', '<span>' + prices[index] + '</span>');
})
答案 1 :(得分:2)
由于您已在注释中指出两个数组中的元素均以正确的顺序排列,所以这种方法(虽然可能不是最优雅的解决方案)应该起作用。
var counter = 0;
for (let value of swatchUl) {
value.insertAdjacentHTML('beforeend', '<span>' + prices[counter++] + '</span>');
}