
本文介绍使用 JavaScript 将 textarea 中的单词按顺序拆分,并分别插入到 class 为 word1、word2… 的 <ol> 元素中,每个单词作为独立 <li> 子项;支持自动清空旧内容、限制最多处理 6 个单词,并通过 CSS 实现统一编号样式。
本文介绍使用 javascript 将 textarea 中的单词按顺序拆分,并分别插入到 class 为 `word1`、`word2`… 的 `
- ` 元素中,每个单词作为独立 `
- ` 子项;支持自动清空旧内容、限制最多处理 6 个单词,并通过 css 实现统一编号样式。
在实际前端开发中,常需将用户输入的文本按词粒度结构化处理。本教程提供一种轻量、可复用的方案:将 <textarea> 中以空格分隔的单词,依次注入预设的多个 <ol> 容器(class 分别为 word1 至 word6),每个单词封装为一个 <li> 元素。
✅ 核心实现逻辑
- 获取并清洗输入:通过 getElementById('textarea') 获取文本域内容,用 .split(' ') 拆分为单词数组;
- 清空已有内容:使用 document.querySelectorAll('ol[class^=word]') 选中所有 class 以 word 开头的 <ol>,遍历清空其 innerHTML,避免重复追加;
- 动态创建与插入:对每个单词(含索引 i),创建 <li> 元素并设置文本内容,再通过 document.querySelector('.word' + (i+1)) 精准定位对应 <ol> 并 append() 插入;
- 安全容错:使用可选链操作符 ?. 防止当单词数超过 6 时因 querySelector 返回 null 导致报错(第七个及之后的单词将被自然忽略)。
? 完整 HTML + JS + CSS 示例
<textarea id="textarea" class="rebaz" rows="4" cols="50">hello my name is rebaz</textarea> <br> <button onclick="show();">Show content</button> <ol class="word1"></ol> <ol class="word2"></ol> <ol class="word3"></ol> <ol class="word4"></ol> <ol class="word5"></ol> <ol class="word6"></ol> <script> function show() { // 清空所有 wordX 类的 ol 元素 document.querySelectorAll('ol[class^=word]').forEach(ol => ol.innerHTML = ''); const source = document.getElementById('textarea'); const words = source.value.trim().split(/\s+/).filter(word => word.length > 0); // 健壮分割:过滤空字符串 words.forEach((word, i) => { if (i >= 6) return; // 严格限制最多处理 6 个单词 const li = document.createElement('li'); li.textContent = word; document.querySelector(`.word${i + 1}`)?.append(li); }); } </script> <style> body { counter-reset: listCounter; } ol[class^="word"] { list-style-type: none; padding: 0; margin: 0.25em 0; } ol[class^="word"] > li { counter-increment: listCounter; border: 1px solid #ccc; padding: 0.5em 1em; margin: 0.25em 0; background-color: #f9f9f9; } ol[class^="word"] > li::before { content: counter(listCounter) ". "; font-weight: bold; color: #333; } button { cursor: pointer; padding: 0.5em 1em; margin-top: 0.5em; background: #007bff; color: white; border: none; border-radius: 4px; } </style>⚠️ 注意事项与最佳实践
- ID 必须唯一:务必为 <textarea> 添加 id="textarea",否则 getElementById 将失效;
- 空格健壮性处理:使用正则 /\s+/ 分割并配合 filter(word => word.length > 0) 可正确处理多个连续空格、首尾空格等边界情况;
- 语义合理性提醒:单 <li> 的 <ol> 在语义上略显冗余(<ol> 本意是“有序列表”,单元素无序意义),若仅需展示,可考虑改用 <div class="wordN"> + CSS 计数器替代;但本方案严格遵循需求,保留 <ol> 结构;
- 扩展性建议:如需支持更多单词,只需增加对应 <ol class="word7"> 等 DOM 节点,并移除 if (i >= 6) return; 限制即可。
该方案简洁高效、兼容主流浏览器,适用于单词解析、逐词高亮、教学演示等场景,兼顾功能性与可维护性。


















