2014-11-02 71 views
-1

我正在處理一個任務,我必須使用javascript將文本打印到文本框區域。用戶被允許輸入他們想要的文本的「對象」和「目的地」。這種方法以前工作沒有文本框,但現在我添加了文本框我有樂趣到無數的錯誤。在查看Chrome的控制檯時,我不斷收到一個錯誤,指出「newVerse()」未定義,即使它明確定義爲函數。任何幫助,將不勝感激。已解決:Javascript函數返回undefined?

<html> 
<head> 
    <script LANGUAGE="JavaScript"> 
     function newVerse() 
     { 

     var objects = document.getElementById('objectsID').value 
     var destination = document.getElementById('destinationID').value 

     var result = "Where have all the " + objects + " gone? <br /> + Long time passing. <br /> + Where have all the " + objects + " gone? <br /> + Long time ago. <br /> + Where have all the " + objects + " gone? <br /> + Gone to " + destination + ", everyone. <br /> + When will they ever learn? <br /> + When will they ever learn? <br />"; 

     result = document.getElementById('textboxid').value 

     } 
    </script> 
</head> 
<body> 
<form> 
<b>Objects Input</b>: <input TYPE="text" NAME="objects1" ID="objectsID" SIZE="20" /> 
<p> 
<b>Destination Input</b>: <input TYPE="text" NAME="destination1" ID="destinationID" SIZE="20" /> 
<p> 
<input TYPE="button" VALUE="Print Verse" onClick="newVerse()" /> 
<p> 
<textarea id="textboxid" rows=10 cols=50> 

</textarea> 
</form> 
</body> 
</html> 
+2

看起來就像你'結果=的document.getElementById( 'textboxid')valu'向後 – Bergi 2014-11-02 17:34:46

+1

。 「*我一直收到一個錯誤,說」newVerse()「是未定義的,即使它明確定義爲函數*」 - 是的,'newVerse'被定義爲一個函數並調用它('newVerse()')不會返回任何事物,因此都是'未定義的'。 – Bergi 2014-11-02 17:35:45

+0

看起來像有人需要學習JavaScript語法的基礎知識 – 2014-11-02 17:38:45

回答

0

這裏是工作代碼:

<html> 
<head> 
</head> 
<body> 
    <form> 
     <b>Objects Input</b>: <input type="text" name="objects1" id="objectsID" size="20" /> 
     <p> 
     <b>Destination Input</b>: <input type="text" name="destination1" id="destinationID"  size="20" /> 
     <p> 
     <input type="button" value="Print Verse" onclick="newVerse()" /> 
     <p> 
     <textarea id="textboxid" rows=10 cols=50></textarea> 
    </form> 

<script language="JavaScript"> 
    function newVerse() { 

     var objects = document.getElementById('objectsID').value; 
     var destination = document.getElementById('destinationID').value; 

     var result = "Where have all the " + objects + " gone? <br /> + Long time passing. <br /> + Where have all the " + objects + " gone? <br /> + Long time ago. <br /> + Where have all the " + objects + " gone? <br /> + Gone to " + destination + ", everyone. <br /> + When will they ever learn? <br /> + When will they ever learn? <br />"; 

     document.getElementById('textboxid').value = result; 

    } 
</script> 

是從原始的代碼改變是在文本框會填充文字的唯一的事情: 因爲你想給一個元素(具有一定的id)的一些內容,那麼你只需鍵入:

document.getElementById("idOfWhatEverElement").value = "This is the content"; 

最後一件事情,就像我自己制定的規則:如果您不在HTML文檔中提供對JavaScript代碼(作爲單獨文件)的引用,那麼不要在頭部鍵入javascript代碼;把它放在身體的盡頭(就像我現在所做的那樣)。這樣你確保JavaScript可以訪問所有DOM元素,因爲它們在腳本本身之前呈現。

最後一兩件事,儘量遵循XHTML標準,像往常一樣使用結束標記的地方是必要的:

<b>something bold</b> and <p>This is a paragraph</p>