格式化由html类

时间:2017-02-22 19:13:30

标签: javascript jquery html

我一直在努力在我的网站上实施一个评论系统,并且在这一点上陷入困​​境:

我将所有只能从购物车页面访问的产品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);

4 个答案:

答案 0 :(得分:2)

使用.map()

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

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

答案 1 :(得分:0)

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

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>

答案 2 :(得分:0)

尝试使用each

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

答案 3 :(得分:0)

纯JS 解决方案(没有jQuery)。

&#13;
&#13;
<span class="ProdSkus">SKU1</span>
<span class="ProdSkus">SKU2</span>
<span class="ProdSkus">SKU3</span>
&#13;
{{1}}
&#13;
&#13;
&#13;