首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計疑難解答

JavaScript 實現「已選條件」標籤邏輯:從數據驅動到 UI 同步的完整方案

     編輯:程式設計疑難解答

電商篩選、數據儀表盤常見「已選條件」區塊,需實現:用戶點選條件 → 標籤顯示在已選區 → 點擊標籤「×」移除條件 → 列表聯動刷新。核心在於單一數據源驅動多視圖同步。

核心數據結構

// 統一狀態管理
const state = {
  selected: new Map() // key: 維度名, value: Set(選中值)
  // 例: { brand: Set(['Apple','Samsung']), price: Set(['1000-2000']) }
};

關鍵操作函數

// 添加條件
function addCondition(dimension, value) {
  if (!state.selected.has(dimension)) state.selected.set(dimension, new Set());
  state.selected.get(dimension).add(value);
  renderAll();
}

// 移除條件
function removeCondition(dimension, value) {
  const set = state.selected.get(dimension);
  if (set) {
    set.delete(value);
    if (set.size === 0) state.selected.delete(dimension);
    renderAll();
  }
}

// 渲染「已選條件」標籤區
function renderTags() {
  const container = document.getElementById('selected-tags');
  container.innerHTML = '';
  state.selected.forEach((values, dim) => {
    values.forEach(val => {
      const tag = document.createElement('span');
      tag.className = 'tag';
      tag.innerHTML = `${dim}: ${val} `;
      container.appendChild(tag);
    });
  });
  // 事件委託綁定移除
  container.onclick = e => {
    if (e.target.tagName === 'BUTTON') {
      removeCondition(e.target.dataset.dim, e.target.dataset.val);
    }
  };
}

// 渲染篩選面板(高亮已選)
function renderPanels() { /* 根據 state.selected 更新 checkbox/radio 狀態 */ }

// 觸發列表查詢
function fetchList() { /* 將 state.selected 序列化為參數調用 API */ }

// 統一入口
function renderAll() {
  renderTags();
  renderPanels();
  fetchList();
}

進階優化

  • 使用 Proxy 監聽 state.selected 變化自動觸發渲染
  • 結合 URL Hash/History API 實現條件可分享、可回退
  • 防抖 fetchList 避免頻繁請求
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved