我跟随add onclick function to a submit button
的回答这是我的HTML:
Name: <input type="text" id="name">
<br>
<br>
<input type="submit" onclick="return process();" />
和JS:
var text = document.getElementById("name").value;
function process() {
alert(text);
return true;
}
点击表单后,会显示:Uncaught ReferenceError: process is not defined
我已经仔细检查了所有内容,并且已经定义了process()
函数。我想知道为什么这不起作用
这里是DEMO
================== UPDATE ========================= =======
我使用SO的代码片段尝试了它,并且它有效。我猜jsfiddle有问题,不知何故javascript和HTML没有连接
function process() {
var text = document.getElementById("name").value;
alert(text);
return true;
}
&#13;
Name: <input type="text" id="name">
<br>
<br>
<input type="submit" onclick="return process();" />
&#13;
答案 0 :(得分:2)
问题在于您的行动顺序。在加载DOM之后,需要附加你的javascript。
Name: <input type="text" id="name">
<br>
<br>
<input type="submit" onclick="return process();" />
<script>
var text = document.getElementById("name").value;
function process() {
alert(text);
return true;
}
</script>
你应该在函数中包含var文本,然后你可以在任何地方加载JS。
Name: <input type="text" id="name">
<br>
<br>
<input type="submit" onclick="return process();" />
<script>
function process() {
var text = document.getElementById("name").value;
alert(text);
return true;
}
</script>
答案 1 :(得分:1)
您收到的错误消息是由于Jsfiddle.net的工作方式。隔离测试,代码运行没有错误。但是,警报文本是空字符串。原因是变量text
在执行开始时只分配一次,然后输入字段为空。
解决此问题的一种方法是将text
变量设置为函数的局部变量,以便在调用函数时为其分配值:
function process() {
var text = document.getElementById("name").value;
alert(text);
return true;
}