为了账号安全,请及时绑定邮箱和手机立即绑定

布尔和条件语句如何在事件监听器中执行?

布尔和条件语句如何在事件监听器中执行?

慕运维8079593 2023-02-17 15:47:32
有人可以在代码中解释这里的逻辑。为什么如果变量“started”已经为 false 并且此事件的条件仅在 started 不是 false 时运行,为什么如果事件侦听器中的条件本身违背变量“started ”的值它会运行?function nextSequence(){ console.log("Hello World"); }var started = false;$("body").on("keydown",function(){   if(!started){      nextSequence();      started=true;}});
查看完整描述

3 回答

?
摇曳的蔷薇

TA贡献1793条经验 获得超6个赞

!布尔值之前反转布尔值。于是就true变成了false。并false成为true


console.log( false ); 
console.log( !false );


PS:它还可以将布尔值以外的另一种类型转换为布尔值并反转该值。但是您不需要知道这个例子。


查看完整回答
反对 回复 2023-02-17
?
偶然的你

TA贡献1841条经验 获得超3个赞

至少你可以这样做:


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)


查看完整回答
反对 回复 2023-02-17
?
心有法竹

TA贡献1866条经验 获得超5个赞

你已经否定了你的 if 条件

它应该是

if(started){}


查看完整回答
反对 回复 2023-02-17
  • 3 回答
  • 0 关注
  • 80 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信