2013-11-02 14 views
0

我是JavaScript新手,我試圖將輸入框中的文本動態添加到段落中(在頁面頂部的2個標題下) 。使用JavaScript動態地將文本框的內容作爲段落文本插入

我有我與here

這是我的函數工作一個的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,它是這樣做的:對象HTMLTextAreaElement]

我不知道我哪裏出錯了。

+0

這個作品:http://jsfiddle.net/shannongmac/T7LeW/12/ – shannonmac

回答

2

您將插入textArea作爲newParagraph中的文本。由於它需要一個字符串時,被轉換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); 

希望我幫助你!

+0

謝謝!好吧,它將它添加到底部,而不是頂部,但我認爲我可以在這方面努力! – shannonmac

+0

它在底部添加,因爲您正在追加newParagraph。加上它,它會按預期工作! :) –

+0

我更改爲「prependChild」,但隨後停止添加文本。嗯... – shannonmac