javascript - 如何替换 contenteditable div 中的文本?
问题描述
在互联网上进行研究后,我找不到适合我的问题的答案。所以我有一个内容可编辑的 div 并且字符串的替换方法不起作用。所以我的想法是我想用任何东西(“”)替换子字符串。subString 只是一个短语,而不是 div 中的整个文本。但是字符串的replace方法没有做任何事情,我尝试调试它但没有运气。newTask() 在这个可内容编辑的 div 中创建另一个 div,因此它可能会改变结果。
这是代码:
var bodyText = document.querySelector(".textarea");
bodyText.addEventListener("keypress", () => {
var key = window.event.keyCode;
if (key === 13) {
var contenteditable = document.querySelector("[contenteditable]");
var text = contenteditable.textContent;
var subString = text.substring(
text.indexOf("!") + 1,
text.lastIndexOf("!")
); //gets specific phrase
// 'subString' phrase is also the thing i wanted it to be replaced
const string = subString;
if (subString !== "") {
console.log(string);
newTask(string);
text.replace(subString, "[][]"); //<--this does not work
}
}
});
function newTask(input) {
var taskDiv = document.createElement("div");
taskDiv.className = "task";
taskDiv.addEventListener("click", () => {
taskDiv.classList.toggle("completed");
});
var textboxDiv = document.createElement("div");
textboxDiv.className = "textbox";
textboxDiv.contentEditable = true;
textboxDiv.innerHTML = input;
taskDiv.appendChild(textboxDiv);
bodyText.appendChild(taskDiv);
}
问我是否需要更多信息。感谢您的帮助!
解决方案
尝试使用下面的代码
const newText=text.replace(subString, "[][]");
contenteditable.textContent=newText;
推荐阅读
- jquery - jQuery Ajax 不会继续处理任何回调 .done、.fail、.always - 为什么?
- machine-learning - keras 神经网络为每个手写数字预测相同的数字
- javascript - 如何检查内容的长度?
- aws-lambda - AWS Lambda 无缘无故返回内部服务器错误
- flutter - Flutter 权限处理程序无法正常工作
- node.js - 你如何解析一个标记为零的nodejs条目?
- javascript - JavaFX Webview:Javascript Bridge 在第二个页面加载时延迟
- javascript - 无法从“date-fns”模拟 startOfToday
- php - SQLSTATE[HY000] [2002] 在带有 XAMPP 的 Mac OS Catalina 上连接被拒绝,在 StackOverflow 上尝试了大多数解决方案
- ruby-on-rails - 使用 Axios 在 ReactJS 中注册的 simple_token_authentication - Rails API