如何使用Javascript实现表格动态样式设置及代码复用?
问题解答
是否需要完全重构代码?
不需要完全重构现有代码逻辑,仅需对重复逻辑做抽象封装、统一处理数据拆分即可满足DRY规范需求。
优化实现思路
- 仅对
data.desc做1次拆分,将结果缓存复用,避免重复执行split()造成不必要的性能损耗 - 将表格生成的重复逻辑抽离为通用函数,所有不同列数的表格都调用同一个函数生成,无需重复编写渲染逻辑
- 段落渲染也复用缓存的拆分结果,消除硬编码的重复逻辑
优化后完整代码
功能实现代码
function loadMountsVehicles() { fetch('https://api.open5e.com/sections/mounts-and-vehicles/') .then(function (responses) { return responses.json(); }).then(function (data) { displayMountsVehicles(data); }); }; // 通用表格生成函数,所有表格统一调用 function generateTable(rawArr, perRow) { // 自动查找分隔线位置并删除对应分隔行 const separatorIndex = rawArr.findIndex(item => item.startsWith('---')); if (separatorIndex > -1) { rawArr.splice(separatorIndex, perRow); } let tableHtml = '<table><thead><tr>'; for (let i = 0; i < rawArr.length; i++) { tableHtml += `<td>${rawArr[i]}</td>`; const next = i + 1; if (i === perRow - 1) { tableHtml += '</thead><tbody>'; } else if (next % perRow === 0 && next !== rawArr.length) { tableHtml += '</tr><tr>'; } } tableHtml += '</tr></tbody></table>'; return tableHtml; } function displayMountsVehicles(data) { let html = "<h3>Mounts and Vehicles</h3>"; // 仅做一次拆分,结果全程复用 const lineArr = data.desc.split(/\n/); const tableRawArr = data.desc.split(/[\n|]+/); // 渲染前16行说明段落 lineArr.slice(0, 16).forEach(line => { html += `<p>${line}</p>`; }); // 生成4列坐骑表格 html += generateTable(tableRawArr.slice(8, 48), 4); // 渲染中间说明段落 lineArr.slice(26, 28).forEach(line => { html += `<p>${line}</p>`; }); // 生成3列马具表格 html += generateTable(tableRawArr.slice(49, 100), 3); // 渲染中间说明段落 lineArr.slice(46, 49).forEach(line => { html += `<p>${line}</p>`; }); // 生成3列水上交通工具表格 html += generateTable(tableRawArr.slice(101), 3); // 统一处理样式替换 html = html.replace(/\*\*\_([\w\(\)][\s\w\,\(\)\.]+)\_\*\*/g, "<span>$1</span>"); html = html.replace(/\*\*([\w\(\)\_][\s\w\,\(\)\_\.]+)\*\*/g, "<span>$1</span>"); document.querySelector(".content-text").innerHTML = html; };
<body onload="loadMountsVehicles()"> <div class="content-text"></div> </body>
返回数据测试代码
function loadMountsVehicles() { fetch('https://api.open5e.com/sections/mounts-and-vehicles/') .then(function (responses) { return responses.json(); }).then(function (data) { console.log(data.desc) }); };
<body onload="loadMountsVehicles()"> </body>
内容的提问来源于stack exchange,提问作者BraulioPortela
相关产品推荐
相关产品推荐

