简体   繁体   English

将文本字段的值返回给JavaScript

[英]Returning the value of a text field to JavaScript

I know this is an extremely basic question but I'm very new to (non-HTML) programming and after taking most of the JS tracks on CodeAcademy, I'm still struggling to make any of the things I've learned actually work. 我知道这是一个非常基本的问题,但是对于(非HTML)编程我还是很陌生,在CodeAcademy上学习了大部分JS知识之后,我仍在努力使我学到的任何东西都可以实际工作。

So I decided as a challenge to myself to design a simple JavaScript-based command line. 因此,我决定设计一个简单的基于JavaScript的命令行作为对我自己的挑战。 Of course, the very first actual code that I write refuses to work, despite constant fiddling. 当然,尽管不断摆弄,我编写的第一个实际代码还是无法正常工作。

Here's the HTML (well, the relevant bit): 这是HTML(相关部分):

<input type="text" id="commandfield"></input>
<button type="button" onclick="enterCommand()">Enter</button>

And here's the Javascript: 这是Javascript:

var field = document.getElementById("commandfield");

function enterCommand () {
    var input = field.value;
    alert(input);
}

...And no alert shows. ...并且没有警报显示。 I tested a plain string alert, and it worked fine, so I know the problem lies with the getting value of #commandfield. 我测试了一个纯字符串警报,它工作正常,因此我知道问题出在#commandfield的获取价值上。 What am I doing wrong? 我究竟做错了什么?

Select the element inside the function: 选择函数内的元素:

function enterCommand () {
    var field = document.getElementById("commandfield");
    if (field) {
        var input = field.value;
        alert(input);
    }
}

This will select the element given the state of the DOM at the time the event occurs. 这将在事件发生时选择给定DOM状态的元素。

function enterCommand () {
    var field = document.getElementById("commandfield");      
    var input = field.value;
    alert(input);
}

Try this,I think you put the script in head tag,not the bottom of the body tag. 试试这个,我想您将脚本放在head标签而不是body标签的底部。

So could not GET that Node 因此无法获取该节点

I tried it, and this works: 我尝试了,这有效:

<script type="text/javascript">
function enterCommand () {
var field = document.getElementById("commandfield");
var input = field.value;
window.alert(input);
}
</script>
<input type="text" name="commandfield" id="commandfield">
<button type="button" onclick="enterCommand()">Enter</button>

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

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