jQuery 如何检查jquery中是否存在变量
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21055231/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
how to check if a variable exists in jquery
提问by ceed
Is there a way to create a variable in jquery/javascript if it not exists?
如果不存在,有没有办法在 jquery/javascript 中创建变量?
i'hv tried:
我试过:
if (moving.length<0) {
moving=false;
}
if (moving=='undefined') {
moving=false;
}
But logicaly it all failes because the initial check on the variable is already undefined
但从逻辑上讲,这一切都失败了,因为对变量的初始检查已经未定义
hope you guys can help :)
希望你们能帮上忙:)
first answer worked properly but my problems whith this continue.
第一个答案工作正常,但我的问题仍在继续。
$.fn.animation = function() {
if (typeof moving == 'undefined') {var moving = false;};
if(moving===false){
var moving=true;
console.log('test');
};
};
$(window).scroll(function(){
if($(window).scrollTop() < scrollpos){
elm.animation();
}
scrollpos=$(window).scrollTop();
});
In this setup 'test' gets constantly loged even if i log moving which is set to true the if still gets ignored.
在此设置中,即使我记录设置为 true 的移动,“测试”也会不断记录,如果仍然被忽略。
so what i want to archive is that everytime i scroll the element get checked if its already animated. If so, dont do the animation.
所以我想要存档的是,每次我滚动元素时都会检查它是否已经动画。如果是这样,不要做动画。
Basicly a queue
基本上是一个队列
回答by adeneo
Did you try
你试过了吗
if (typeof moving == 'undefined') var moving = false;
In some cases I use
在某些情况下,我使用
var moving = typeof moving == 'undefined' ? false : moving;
which is basically the same, but for me it's more readable in some cases to see that the variable is set, either to it's original value, or false
if it's undeclared, but the first version is more common.
这基本上是一样的,但对我来说,在某些情况下,看到变量被设置为它的原始值,或者false
如果它未声明,它更具可读性,但第一个版本更常见。
EDIT:
编辑:
Here's how to detect scroll
这是检测滚动的方法
var scrolled = false;
$(window).on('scroll', function() {
scrolled = true;
});
//later
if (scrolled) {
// do stuff
}
回答by deW1
if( typeof moving === 'undefined' )
{
var moving;
moving = false;
}
Will work.
将工作。