2014-11-02 68 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>