使用 JavaScript 将文本框的内容作为段落文本动态插入

Insert the contents of a textbox as paragraph text dynamically with JavaScript

本文关键字:文本 段落 动态 插入 JavaScript 使用      更新时间:2023-09-26

我是 JavaScript 的新手,我正在尝试将输入框中的文本动态添加到段落中(在页面顶部的 2 个标题下)。

有一个JSFiddle,我在这里工作

这是我的函数:

    function addText() {
            var newParagraph = document.createElement('p');
        newParagraph.textContent = textArea;
        document.getElementById("id1").appendChild(newParagraph);
        myDiv.insertBefore(newParagraph, textArea);
        }
    document.getElementById("textArea").onblur = addText;

但是,正如你所看到的,在onblur上,它正在这样做:[object HTMLTextAreaElement]

不确定我哪里出错了。

您将文本区域作为文本插入到新段落中。因为它需要一个字符串,是将textArea转换为字符串表示,即"[对象HTMLTextAreaElement]"

相反,请执行此操作:

newParagraph.textContent = textArea.value;

然后,您的代码将是:

    function addText() {
        var newParagraph = document.createElement('p');
        newParagraph.textContent = textArea.value;
        document.getElementById("id1").appendChild(newParagraph);
        myDiv.insertBefore(newParagraph, textArea);
    }
    document.getElementById("textArea").onblur = addText;

正如您告诉我的,您想在新段落前面加上,请使用以下内容:

     parentObject.insertBefore(newParagraph, parentObject.firstChild);

希望我能帮到你!