index.js 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. // 获取文档结构
  2. async function loadDocumentStructure() {
  3. const loading = document.getElementById('loading');
  4. const error = document.getElementById('error');
  5. const container = document.getElementById('categories-container');
  6. try {
  7. const response = await fetch('/api/structure');
  8. if (!response.ok) {
  9. const errorData = await response.json().catch(() => ({}));
  10. throw new Error(errorData.error || `加载失败 (${response.status})`);
  11. }
  12. const structure = await response.json();
  13. // 验证数据结构
  14. if (!Array.isArray(structure) || structure.length === 0) {
  15. throw new Error('文档结构为空或格式错误');
  16. }
  17. // 隐藏加载提示
  18. loading.style.display = 'none';
  19. // 渲染分类卡片
  20. renderCategories(structure);
  21. } catch (err) {
  22. console.error('Error loading structure:', err);
  23. loading.style.display = 'none';
  24. error.style.display = 'block';
  25. error.textContent = `加载失败:${err.message || '请稍后重试'}`;
  26. }
  27. }
  28. // 渲染分类卡片
  29. function renderCategories(structure) {
  30. const container = document.getElementById('categories-container');
  31. structure.forEach(category => {
  32. const card = document.createElement('div');
  33. card.className = 'category-card';
  34. const title = document.createElement('h2');
  35. title.className = 'category-title';
  36. title.textContent = category.name;
  37. const docCount = document.createElement('p');
  38. docCount.className = 'doc-count';
  39. docCount.textContent = `${category.docs.length} 篇文档`;
  40. const button = document.createElement('button');
  41. button.className = 'read-btn';
  42. button.textContent = '开始阅读';
  43. button.onclick = () => {
  44. // 跳转到阅读页,并传递分类名
  45. window.location.href = `/reader.html?category=${encodeURIComponent(category.name)}`;
  46. };
  47. card.appendChild(title);
  48. card.appendChild(docCount);
  49. card.appendChild(button);
  50. container.appendChild(card);
  51. });
  52. }
  53. // 页面加载时执行
  54. document.addEventListener('DOMContentLoaded', loadDocumentStructure);