格式化由 html 类 组成的数组

Formatting Array made from html classes

我一直致力于在我的网站中实施审查系统,但卡在了这一点上:

我采用了所有只能从购物车页面访问的产品 SKU,如下所示:

<span class="ProdSkus">SKU1</span>
<span class="ProdSkus">SKU2</span>
<span class="ProdSkus">SKU3</span>

我将这些组合成一个数组:

var combinedText = $('.ProdSkus').text();

当我记录它时,我得到了这个结果:

SKU1SKU2SKU3

我需要将其格式化为:

["SKU1", "SKU2", ...]

感谢任何帮助!

这必须从购物车页面完成,存储在本地,然后在客户购买后使用。我一直这样做:

localStorage.setItem("SKUS", combinedText);

您可以迭代元素集并将每个值添加到数组中:

var combinedText = [];  // This is where the results will go

// Loop over the matched elements
$('.ProdSkus').each(function(){
  // Add the text of each span to the array
  combinedText.push(this.textContent);
});

// Test the result
console.log(combinedText);

// And, to store the values in localStorage,
// you'd need to convert the array into a string
// This will throw an error here in Stack Overflow because
// their snippet environment doesn't allow it, but the code is correct:
localStorage.setItem("combinedText", JSON.stringify(combinedText));

// Then, when/where you want the data back out of localStorage, you'd write
var gottenData = localStorage.getItem("combinedText");
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span class="ProdSkus">SKU1</span>
<span class="ProdSkus">SKU2</span>
<span class="ProdSkus">SKU3</span>

使用.map():

var combinedText = $('.ProdSkus').map(function() {
    return $(this).text();
}).get();

.map() return 是 return 值(在本例中为字符串)的 jQuery 集合,.get() 将其转换为数组。

尝试使用 each:

var combinedText = [];
$('.ProdSkus').each(function(k,v) {
    combinedText.push(v.text());
});
console.log(combinedText);

纯JS解决方案(无jQuery)。

var elems = document.getElementsByClassName('ProdSkus');
var arr = [];
Array.from(elems).forEach(v => arr.push(v.innerHTML));

console.log(arr);
<span class="ProdSkus">SKU1</span>
<span class="ProdSkus">SKU2</span>
<span class="ProdSkus">SKU3</span>