首页 > 文章列表 > 如何用JS动态展示树形结构的平台和期限数据并更新价格?

如何用JS动态展示树形结构的平台和期限数据并更新价格?

500 2025-04-07

JS 遍历树形数据,动态展示平台和期限数据

要实现上述需求,可以使用 JS 遍历后台返回的树形数据,动态生成 DOM 元素来展示平台和期限选项。

// 遍历后台数据
function generateOptions(data) {
  for (const platform of data) {
    // 创建平台选择项
    const platformOption = document.createElement('option');
    platformOption.value = platform.title;
    platformOption.innerHTML = platform.title;

    // 为期限选择项添加事件监听器
    platformOption.addEventListener('change', e => {
      togglePeriodOptions(e.target.value, true);
    });

    // 向授权平台下拉菜单中添加平台选择项
    document.querySelector('.select.au_plat').appendChild(platformOption);

    // 为每个平台下的期限生成选项
    for (const period of platform.children) {
      generatePeriodOption(period, platform.title);
    }
  }

  // 首次加载时显示第一个平台的期限选项
  togglePeriodOptions(data[0].title, false);
}

// 生成期限选择项
function generatePeriodOption(period, platform) {
  const periodOption = document.createElement('option');
  periodOption.value = period.id;
  periodOption.innerHTML = `${period.show_title}`;

  // 为授权期限下拉菜单中添加期限选择项
  document.querySelector('.select.au_per').appendChild(periodOption);

  // 为期限选择项添加事件监听器
  periodOption.addEventListener('change', e => {
    updatePrice(platform, e.target.value);
  });
}

// 根据选择的平台和期限更新价格显示
function updatePrice(platform, periodId) {
  const price = data.find(p => p.title === platform)
    .children
    .find(c => c.id === Number(periodId))
    .price;

  document.querySelector('.price').innerHTML = `¥${price}`;
}

// 切换期限选择项的显示
function togglePeriodOptions(platform, firstLoad) {
  // 获取平台下的期限选择项
  const periodOptions = document.querySelectorAll('.select.au_per option');

  // 隐藏所有期限选择项
  periodOptions.forEach(option => {
    option.style.display = 'none';
  });

  // 根据选定的平台显示对应的期限选择项
  const periods = data.find(d => d.title === platform)?.children;
  if (periods) {
    periods.forEach(period => {
      periodOptions.forEach(option => {
        if (option.value === period.id.toString()) {
          option.style.display = 'block';
        }
      });
    });

    // 首次加载时选中第一个期限
    if (firstLoad) {
      const firstPeriod = periods[0];
      updatePrice(platform, firstPeriod.id);
      document.querySelectorAll('.select.au_per option')[firstPeriod.id - 1].selected = true;
    }
  }
}

window.onload = () => {
  // 调用函数遍历后台数据
  generateOptions(price_list);
};

在给定的 HTML 元素中,直接使用该 JavaScript 代码,即可实现树形数据遍历,动态展示平台和期限选项,以及根据用户选择更新价格显示的功能。

来源:1740303092