简体   繁体   English

javascript全局变量未定义

[英]javascript global variable undefined

I have a problem with a javascript global variable, let's suppose I have the following 我的javascript全局变量有问题,让我们假设我有以下问题

var globalVar;

I have a text field 我有一个文本字段

<input type="text" id="myInput" onkeydown="checkKey(this)" onkeypress="checkKey(this)"/>

And in the function checkkey, I assign some value to it: 然后在功能Checkkey中,给它分配一些值:

globalVar=document.forms[0].elements("myInput").value;

I checked the the global variable value has changed with an alert. 我检查了全局变量值是否已更改并发出警报。 When I try to use globalVar in another function, I find it has the value undefined. 当我尝试在另一个函数中使用globalVar时,我发现它的值未定义。 The other function has something like: 另一个功能类似于:

param += globalVar;

The elements property of form instances isn't a function, it's an object. form实例的elements属性不是函数,而是对象。 Use 采用

globalVar=document.forms[0].elements.myInput.value;

...or ...要么

globalVar=document.forms[0].elements["myInput"].value;

...but better yet, with the way you're calling checkKey , just declare an argument called input or whatever and use ...但更好的是,通过调用checkKey的方式,只需声明一个名为input或其他任何参数的参数并使用

globalVar=input.value;

...since you're passing this into checkKey . ......因为你传递thischeckKey

If you're going to access the form field by its name as you have, use the name attribute rather than the id attribute (although id will work on many browsers as well). 如果要按名称访问表单字段,请使用name属性而不是id属性(尽管id在许多浏览器中也适用)。

If your var globalVar; 如果您的var globalVar; is at global scope (outside of all functions), then it is a global variable. 在全局范围内(在所有功能之外),则它是一个全局变量。 If that var statement is inside a function, it's a local variable. 如果该var语句在函数内部,则为局部变量。 You haven't given us enough context to know where the var is, but if it's at global scope, and you successfully set its value, and later you check it, it will be set. 您没有给我们足够的上下文来知道var在哪里,但是如果它在全局范围内,并且您成功设置了它的值,然后您对其进行了检查,那么它将被设置。

Live demo using the long form | 使用长格式的现场演示 | Live demo using the argument 使用参数进行现场演示

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

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