首页 > 解决方案 > 如何在 contenteditable div 中抓取某些单词

问题描述

编辑:textarea - > contenteditable div

我正在尝试制作一个脚本工具,它从 contenteditable div 中获取某个单词,然后将其更改为另一个单词。

为了更清楚地向您展示我的目标,该工具应该“看起来像”下面的代码段(尽管脚本尚未准备好):通过单击按钮,this is a sample text, this is another text应将其替换为that is a sample text, that is another text. 所有两个thiss 都切换到thats。

<div contenteditable="true">this is a sample text, this is another text</div><br>
<button>change 'this' to 'that'</button>

所以我遇到了我的第一个问题;什么是在内容可编辑的 div 中抓取整个文本中的所有“特定单词”的方法?Jquery 解决方案也可能会有所帮助。

标签: javascripthtmljquery

解决方案


我在这里为您的按钮和文本区域添加了一个 ID。

为此,您可以向按钮元素添加一个事件侦听器并让它侦听单击事件。

当按钮被按下时,使用 textContent 属性获取 div 的文本并使用 textContent 属性重新评估它,但使用replaceAll()方法将所有出现的旧词替换为新词。

document.getElementById('btn').addEventListener('click', replacer);

function replacer(){
let tx = document.getElementById('txarea');
tx.textContent = tx.textContent.replaceAll('this', 'that');
}
<div id="txarea">this is a sample text, this is another text</div><br>
<button id="btn">change 'this' to 'that'</button>


推荐阅读