技术饭
jQuery动态生成商品属性sku组合列表
jQuery动态生成商品属性sku组合列表,最近做商城遇到商品需要添加多种属性规格,无法解决的问题在于各种属性的排列组合,如:[白色,黑色,红色]、[165CM,170CM,175CM]、[4G+64GB,8G+128GB],这三种组合可以组成3 * 3 * 2 = 18种组合。
<!DOCTYPE html>
<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<style type="text/css">
* { padding: 0; margin: 0; }
.demo { padding: 10px; }
.demo table { border-collapse: collapse; }
.demo table tr td { border: 1px solid #ccc; padding: 4px; }
</style>
</head>
<body>
<div id="demo" class="demo"></div>
<script type="text/javascript">
//重点是这个组合方法
function combine(arr) {
arr.reverse();
var r = [];
(function f(t, a, n) {
if (n == 0) return r.push(t);
for (var i = 0; i < a[n-1].length; i++) {
f(t.concat(a[n-1][i]), a, n - 1);
}
})([], arr, arr.length);
return r;
}
var arr = [
['白色','红色', '蓝色'],
['165CM', '170CM', '175CM'],
['4G+64GB','8G+128GB']];
var res = combine(arr);
console.log(res);
//合并单元格
var row = [];
var rowspan = res.length;
for(var n=arr.length-1; n>-1; n--) {
row[n] = parseInt(rowspan/arr[n].length);
rowspan = row[n];
}
row.reverse();
//table tr td
var str = "";
var len = res[0].length;
for (var i=0; i<res.length; i++) {
var tmp = "";
for(var j=0; j<len; j++) {
if(i%row[j]==0 && row[j]>1) {
tmp += "<td rowspan='"+ row[j] +"'>"+res[i][j]+"</td>";
}else if(row[j]==1){
tmp += "<td>"+res[i][j]+"</td>";
}
}
str += "<tr>" + tmp + "<td>xxx</td>" + "<td>xxx</td>" + "</tr>";
}
//thead
var th = "";
for(var k=0; k<len; k++) {
th += "<th>"+ k +"</th>";
}
th = "<thead>"+th+"<th>价格</th>" + "<th>数量</th>" +"</thead>";
str = "<table>" + th + str + "</table>";
document.getElementById('demo').innerHTML = str;
</script>
</body>
</html>
处理结果:
参考链接:https://liu86th.iteye.com/blog/1901650
文明上网理性发言!