js商品规格实现
商品规格实现(JavaScript)
数据结构设计
使用嵌套对象或数组存储规格信息,例如:
const specs = {
"颜色": ["红色", "蓝色", "黑色"],
"内存": ["64GB", "128GB", "256GB"],
"版本": ["标准版", "Pro版"]
}
动态渲染规格选择
通过遍历数据结构生成DOM元素:

function renderSpecs() {
const container = document.getElementById('spec-container');
Object.keys(specs).forEach(key => {
const specGroup = document.createElement('div');
specGroup.innerHTML = `<h3>${key}</h3>`;
specs[key].forEach(value => {
const btn = document.createElement('button');
btn.textContent = value;
btn.onclick = () => selectSpec(key, value);
specGroup.appendChild(btn);
});
container.appendChild(specGroup);
});
}
规格选择逻辑
维护已选规格的状态对象:
let selectedSpecs = {};
function selectSpec(key, value) {
selectedSpecs[key] = value;
checkAvailability();
updatePrice();
}
库存校验
根据组合规格检查库存:

const inventory = {
"红色_64GB_标准版": 10,
"蓝色_128GB_Pro版": 5
};
function checkAvailability() {
const specKey = Object.values(selectedSpecs).join('_');
return inventory[specKey] > 0;
}
价格计算
根据规格组合动态计算价格:
const priceMatrix = {
"64GB": { "标准版": 3999, "Pro版": 4599 },
"128GB": { "标准版": 4299, "Pro版": 4999 }
};
function updatePrice() {
if (selectedSpecs.内存 && selectedSpecs.版本) {
const price = priceMatrix[selectedSpecs.内存][selectedSpecs.版本];
document.getElementById('price').textContent = price;
}
}
交互优化
添加视觉反馈和禁用状态:
function updateUI() {
const allButtons = document.querySelectorAll('#spec-container button');
allButtons.forEach(btn => {
btn.classList.remove('active', 'disabled');
const [key, value] = btn.dataset.spec.split('|');
if (selectedSpecs[key] === value) {
btn.classList.add('active');
}
if (!isSpecAvailable(key, value)) {
btn.classList.add('disabled');
}
});
}
完整实现流程
- 初始化时调用
renderSpecs()加载所有规格选项 - 用户点击时触发
selectSpec()更新选择状态 - 每次选择后执行
checkAvailability()验证库存 - 通过
updatePrice()显示实时价格 - 使用
updateUI()提供视觉反馈
注意事项
- 需要处理规格间的依赖关系(如某些颜色不提供特定版本)
- 移动端需考虑触摸交互优化
- 可添加规格图片展示功能
- 建议使用Vue/React等框架管理状态会更高效






