JS/JQuery如何根据JSON字符串生成含列表项的HTML DOM结构
实现方案
首先修正原代码的两个基础问题:
- 内层循环取值索引错误:原代码用
dataString[i]取值,i是外层数据的索引,应该用内层循环的索引j取当前片段 - 缺少内容类型判断逻辑:没有区分普通段落和带序号的列表内容,也没有处理连续列表项的包裹逻辑
核心判断逻辑用正则匹配片段开头的序号标记,维护当前列表的拼接状态,连续同类型的序号项统一包裹在同一个<ol>标签内,序号样式完全通过CSS控制,不需要保留文本里自带的1.、a.前缀避免重复显示。
完整实现代码
const data = [ { "id" : "1", "prepare" : "Hello welcome to xyz portal || 1. Please login to system || 2. Open dashboard || Verify your details and confirm." }, { "id" : "2", "prepare" : "Hello welcome to portal || a. Please click on link || b. Open the details list items || Check and confirm the details." } ]; function generateContentHtml(dataList) { const htmlParts = []; // 匹配数字序号、小写字母序号开头的正则,分组提取序号后的真实内容 const numItemReg = /^\s*\d+\.\s*(.*)$/; const letterItemReg = /^\s*[a-z]\.\s*(.*)$/; dataList.forEach(item => { // 拆分片段并去除前后多余空格 const segments = item.prepare.split('||').map(seg => seg.trim()); // 标记当前正在拼接的列表类型:num=数字序号列表,letter=字母序号列表,null=当前不在列表块内 let activeListType = null; segments.forEach(seg => { const isNumItem = numItemReg.test(seg); const isLetterItem = letterItemReg.test(seg); if (isNumItem) { // 处理数字序号项 if (activeListType !== 'num') { // 若之前有未闭合的其他类型列表,先闭合 if (activeListType) htmlParts.push('</ol>'); // 开启新的数字序号列表 htmlParts.push('<ol class="list-num">'); activeListType = 'num'; } // 提取去掉序号前缀的内容放入li const content = seg.match(numItemReg)[1]; htmlParts.push(`<li>${content}</li>`); } else if (isLetterItem) { // 处理字母序号项 if (activeListType !== 'letter') { if (activeListType) htmlParts.push('</ol>'); htmlParts.push('<ol class="list-letter">'); activeListType = 'letter'; } const content = seg.match(letterItemReg)[1]; htmlParts.push(`<li>${content}</li>`); } else { // 处理普通段落 if (activeListType) { // 先闭合之前未结束的列表 htmlParts.push('</ol>'); activeListType = null; } htmlParts.push(`<p>${seg}</p>`); } }); // 单条数据遍历结束,闭合剩余未关的列表标签 if (activeListType) { htmlParts.push('</ol>'); activeListType = null; } }); return `<div class="content-wrap">${htmlParts.join('')}</div>`; } // 生成最终DOM字符串 const htmlDOM = generateContentHtml(data);
配套CSS样式
通过list-style-type控制不同列表的序号样式,不需要修改JS逻辑:
.content-wrap p { margin: 12px 0; line-height: 1.5; } /* 数字序号列表样式 */ .list-num { list-style-type: decimal; margin: 10px 0; padding-left: 2em; line-height: 1.5; } /* 字母序号列表样式 */ .list-letter { list-style-type: lower-alpha; margin: 10px 0; padding-left: 2em; line-height: 1.5; }
生成效果说明
对于输入的测试数据,最终生成的HTML结构如下,完全符合需求:
<div class="content-wrap"> <p>Hello welcome to xyz portal</p> <ol class="list-num"> <li>Please login to system</li> <li>Open dashboard</li> </ol> <p>Verify your details and confirm.</p> <p>Hello welcome to portal</p> <ol class="list-letter"> <li>Please click on link</li> <li>Open the details list items</li> </ol> <p>Check and confirm the details.</p> </div>
内容的提问来源于stack exchange,提问作者Siva_K22
相关产品推荐
相关产品推荐

