【发布时间】:2016-04-12 19:35:40
【问题描述】:
如果模组可以帮助我更好地表达我的问题,我将不胜感激,因为如果不提供示例就很难提出这个问题。这是我创建的一个函数:
$("#myField").on('keyup', function(event){
var input = $(this),
val = input.val(),
inputGroup = input.parents('div.input-group')
searchingIcon = $(inputGroup).find('i.auto-spinner'),
button = $(inputGroup).find('span.input-group-btn > button.btn'),
key = event.which,
typingTimer; // This throws an error typingTimer is not defined
//Clear typing timeout on keypress
clearTimeout(typingTimer);
//.... more code below.. not important
});
如您所见,我喜欢用一个简单的 var 声明,后跟逗号来声明我的 var,但是,在这种情况下,当我进入 typingTimer 时,我得到一个未定义的 var 错误,就好像它正在寻找变量一样,而不是定义一个空变量。如果我只是把事情改成这样:
$("#myField").on('keyup', function(event){
var input = $(this),
val = input.val(),
inputGroup = input.parents('div.input-group')
searchingIcon = $(inputGroup).find('i.auto-spinner'),
button = $(inputGroup).find('span.input-group-btn > button.btn'),
key = event.which;
var typingTimer; // All is well again...
//Clear typing timeout on keypress
clearTimeout(typingTimer);
//.... more code below.. not important
});
一切都会好起来的。这不是我第一次遇到这种现象,我真的不知道它的原因。我如何定义不由 (;) 分隔的变量是否有一些限制?
【问题讨论】:
-
您在
inputGroup声明后缺少逗号,导致该行后自动出现分号。因此,所有后续的赋值都不是声明;它们只是对现有变量的赋值(如果不存在同名变量,则赋值给隐式全局变量)。我不确定是否将其作为拼写错误关闭,或者回答它,因为其他人可能会犯同样的拼写错误? -
“这不是我第一次遇到这种现象”:也许是时候改变声明变量的方式了?
-
确实如此。这不是现象,是代码不正确。
标签: javascript variables