问题描述
有人可以在代码中解释逻辑吗?如果变量“ started” 已经为假,并且为什么该事件的条件仅在started不是false时才运行,为什么会运行,为什么如果事件侦听器内部的条件本身违背了该变量的值,为什么会运行变量“开始” ?
function nextSequence(){
console.log("Hello World");
}
var started = false;
$("body").on("keydown",function(){
if(!started){
nextSequence();
started=true;
}
});
解决方法
布尔值之前的!
会使布尔值求反。因此true
成为false
。并且false
变成true
。
console.log( false );
console.log( !false );
PS:它也可以将除布尔值以外的其他类型转换为布尔值并反转该值。但是对于本例,您不需要知道这一点。
,至少您可以做到:
function nextSequence(){
console.log('Hello World');
$('body').off('keydown',nextSequence );
}
$('body').on('keydown',nextSequence );
或更好(感谢 Phil )
$('body').one('keydown',function() {
console.log('Hello World');
})
或在纯JS中:
function firstSequence(){
console.log('Hello World');
document.removeEventListener('keydown',firstSequence)
}
document.addEventListener('keydown',firstSequence)
,
您已经否定了条件
应该是
if(started){}