首页 > 解决方案 > 带有布尔值的 javascript if 语句不起作用

问题描述

我有一个 mouseover 和 mouseenter 函数,只有在我的变量未设置为 true 时才有效。但是鼠标功能无论如何都会触发。

If 语句检查变量是否为 NOT TRUE,但它似乎没有在我设置的情况下工作。click 函数将变量设置为 true,因此当它被单击时,我应该看不到 mouseover 函数正在工作,直到我将“已执行”设置回 false。

任何指导表示赞赏

var executed = false;

if (executed != true) {
    $('.elm').mouseover(function(event) {
        // do something only if variable is not set to true
    })
};
if (executed != true) {
    $('.elm').mouseout(function(event) {
        // do something only if variable is not set to true
    })
};

$('.elm').click(function() {
    // do something and set variable to true
    executed = true;

});

标签: javascriptif-statementboolean

解决方案


您的if语句仅确定mouseover/mouseout事件处理程序是否已注册。他们是,因为false是……嗯,不是真的。

后来,值发生了executed变化,但不再重要了,因为那些if语句不再执行。事件处理程序已经注册并被调用。

您可能想要这样做:

$('.elm').mouseover(function(event) {
  if (executed != true) {
    // do something only if variable is not set to true
  }
});

即总是注册回调,但每次调用时都要检查函数内部executed的变量。

你可以稍微简化一下这个逻辑:

$('.elm').mouseover(function(event) {
  if (executed) {
    return;
  }
  // do something only if variable is not set to true
});

executed如果是真的,就早点回来。这样您就不必将整个函数体包装在if语句中。


推荐阅读