18910140161

JavaScript-如何替换contenteditable div中的文本?-堆栈溢出

顺晟科技

2022-10-19 13:22:56

134

在网上搜索后,我找不到适合我的问题的答案。所以我有一个contenteditable div,字符串的replace方法不起作用。所以想法是我想用nothing(“”)替换子字符串。子字符串只是一个短语,而不是div中的整个文本。但是字符串的replace方法什么都不能做,我试着调试它,但没有成功。newTask()在这个contenteditable 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);
}

  • TAG:
相关文章
我们已经准备好了,你呢?
2024我们与您携手共赢,为您的企业形象保驾护航