HTML输入提交onclick'不起作用

HTML input submit onclick doesn't work

本文关键字:不起作用 onclick 输入 提交 HTML      更新时间:2023-09-26

我正在跟踪向提交按钮添加onclick函数的答案

这是我的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()函数。我想知道为什么不起作用

这是演示

===============更新=========================

我使用SO的代码片段进行了尝试,结果成功了。我想jsfiddle有问题,不知何故javascript和HTML没有连接

function process() {
    var text = document.getElementById("name").value;
  
    alert(text);
    return true;
}
Name: <input type="text" id="name">
<br>
<br>
<input type="submit" onclick="return process();" />

问题在于您的操作顺序。您的javascript需要在DOM加载后追加。

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>

您收到的错误消息是由于Jsfidle.net的工作方式造成的。经过隔离测试,代码运行时没有错误。但是,提醒的文本是空字符串。原因是变量text在执行开始时只分配了一次,然后输入字段为空。

解决此问题的一种方法是使text变量成为函数的本地变量,以便在调用函数时为其分配一个值:

function process() {
    var text = document.getElementById("name").value;
    alert(text);
    return true;
}