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

时间:2013-11-02 21:22:44

标签: javascript html

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

我有一个JSFiddle,我正在使用here

这是我的功能:

    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]

我不确定我哪里出错了。

1 个答案:

答案 0 :(得分:2)

您正在将textArea作为文本插入newParagraph中。因为它需要一个字符串,就是将textArea转换为字符串表示形式,即“[object 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);

希望我能帮助你!

相关问题