Javascript“变量未定义”

时间:2011-03-31 18:26:46

标签: javascript html

我正在编写一个简单的javascript函数,用于从三个文本区域中获取信息。非常基本,但由于某种原因,javascript告诉我我的变量没有定义,我对此感到困惑。

html如下:

<input type = "text" id = "month" name = "month"/>
    <input type = "text" id = "day" name = "day"/>
    <input type = "text" id = "year" name = "year"/>
    <input type = "button" id = "submit" value = "Go!" onClick = "calculate(month, day, year)"/>

javascript只是

function calculate(month, day, year){
var setMonth = document.getElementById(month).value;
var setDay = document.getElementById(day).value;
var setYear = document.getElementById(year).value;}

当我运行它并单击我的按钮时,它在Firebug中显示“月份未定义”。所以我有点困惑,因为......他们被定义了!

帮助?谢谢!

6 个答案:

答案 0 :(得分:10)

monthdayyear被解释为变量名称,这些名称不存在。你想传递字符串:

onClick = "calculate('month', 'day', 'year')"/>

答案 1 :(得分:1)

你没有定义它们:要做到这一点:

calculate('a', 'b', 'c');

在你的情况下,你需要改变你的代码或改变你的功能:

我会说做选项2:

onclick ="calculate(document.getElementById('month'), document.getElementById('day'), document.getElementById('year'));"

和功能:

function calculate(month, day, year){
   var setMonth = month.value;
   var setDay = day.value;
   var setYear = year.value;
}

答案 2 :(得分:1)

请注意,calculate函数没有任何参数,而且 根据字段名称查询文档。

HTML

<input type = "text" id = "month" name = "month"/>
    <input type = "text" id = "day" name = "day"/>
    <input type = "text" id = "year" name = "year"/>
    <input type = "button" id = "submit" value = "Go!" onClick = "calculate()"/>

Javascript

function calculate(){
var setMonth = document.getElementById('month').value;
var setDay = document.getElementById('day').value;
var setYear = document.getElementById('year').value;}

答案 3 :(得分:0)

在html的“onClick”部分,您尝试发送尚未定义的“月”,“日”和“年”变量。

不要传递变量,只需运行“calculate();”函数,从函数中获取表单中的数据。

答案 4 :(得分:0)

调用函数时,必须传递参数initiates

<input type = "text" id = "month" name = "month"/> <input type = "text" id = "day" name = "day"/> <input type = "text" id = "year" name = "year"/> <input type = "button" id = "submit" value = "Go!" onClick = "calculate(document.getElementById(month), document.getElementById(day), document.getElementById(year))"/>

Javascript代码:

function calculate(month, day, year){
var setMonth = month.value;
var setDay = day.value;
var setYear = year.value;}

答案 5 :(得分:0)

如果你想使用函数$(document).ready(...)

您需要在<HEAD></HEAD>标记中添加以下行:


<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>