简体   繁体   English

HTML输入提交onclick不起作用

[英]HTML input submit onclick doesn't work

I'm following the answer from add onclick function to a submit button 我正在从添加onclick函数到提交按钮的答案

Here's my HTML: 这是我的HTML:

Name: <input type="text" id="name">
<br>
<br>
<input type="submit" onclick="return process();" />

and JS: 和JS:

var text = document.getElementById("name").value;

function process() {
    alert(text);
    return true;
}

When I click the form, it says: Uncaught ReferenceError: process is not defined 当我单击该窗体时,它说: Uncaught ReferenceError: process is not defined

I have double checked everything, and the process() function is already defined. 我已经仔细检查了所有内容,并且已经定义了process()函数。 I wonder why this doesn't work 我不知道为什么这行不通

Here's the DEMO 这是演示

==================UPDATE================================ ==================更新=============================== =

I tried it using SO's code snippet, and it worked. 我使用SO的代码段对其进行了尝试,并且成功了。 I guess there's something wrong with jsfiddle, somehow the javascript and HTML are not conected 我想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();" /> 

The problem is your order of actions. 问题是您的行动顺序。 Your javascript needs to be appended after the DOM loads. 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>

And you should actually include var text within the function then you can load the JS wherever. 并且您实际上应该在函数中包含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>

The error message you get is due to the way Jsfiddle.net works. 您收到的错误消息是由于Jsfiddle.net的工作方式引起的。 Tested in isolation, the code runs without errors. 经过独立测试,代码运行无误。 However, the alerted text is the empty string. 但是,警告文本为空字符串。 The reason is that the variable text is assigned only once, at the start of execution, and then the input field is empty. 原因是在执行开始时,变量text仅分配一次,然后输入字段为空。

One way to fix this is to make the text variable local to the function, so that it will be assigned a value whenever the function is invoked: 解决此问题的一种方法是使text变量在函数中本地化,以便在调用函数时为它分配一个值:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM