如何点击段落特定单词添加<span>标签?点击新单词迁移标签至目标单词
实现点击单词添加/转移标签的方案
需求说明
- 点击段落中的任意单词,为该单词添加带样式的
<span>标签 - 点击第二个单词时,将第一个单词的
<span>标签转移到第二个,第一个单词恢复原样
修改后的代码实现
HTML 结构
<p><html></p> <p><p></p> <p class="target-paragraph">The word hashtag is in this sentence. Another hashtag here.</p> <p></p></p> <p></html></p>
JavaScript 逻辑(基于jQuery)
$(document).ready(function() { // 目标段落元素 const $targetPara = $('.target-paragraph'); // 将段落文本拆分为单个单词,包裹成可点击的元素 const textContent = $targetPara.text(); const wordList = textContent.split(/\s+/); const wordNodes = wordList.map(word => `<span class="clickable-word">${word}</span>`); $targetPara.html(wordNodes.join(' ')); // 记录当前被标记的单词元素 let activeElement = null; // 绑定单词点击事件 $('.clickable-word').on('click', function() { const $clickedWord = $(this); // 点击已标记的单词,取消标记 if ($clickedWord.is(activeElement)) { activeElement.replaceWith(activeElement.text()); activeElement = null; return; } // 移除之前的标记 if (activeElement) { activeElement.replaceWith(activeElement.text()); } // 为当前点击的单词添加标记span const markedWord = $(`<span style="color: red;">${$clickedWord.text()}</span>`); $clickedWord.replaceWith(markedWord); activeElement = markedWord; }); });
代码说明
- 初始化处理:把目标段落的文本拆分成单个单词,每个单词用
<span class="clickable-word">包裹,确保能精准捕获点击事件。 - 状态记录:用
activeElement变量保存当前被标记的单词元素,方便后续转移标签时定位。 - 点击逻辑:
- 如果点击的是已标记的单词,直接还原成纯文本并清空状态。
- 如果已有标记的单词,先将其还原,再给当前点击的单词包裹带样式的
<span>。 - 最后更新
activeElement为新标记的元素。
内容的提问来源于stack exchange,提问作者user12585152
相关产品推荐
相关产品推荐

