javascript - 带有布尔值的 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;
});
解决方案
您的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
语句中。
推荐阅读
- java - 在Java中根据字符串名称获取变量的值
- java - 运行时权限在每次被拒绝时返回
- c - 我的程序在 C 中到达 scanf() 语句后崩溃并停止工作
- automation - 用硬回报代替软回报
- assembly - 检查是否启用了特定中断( IPI )
- hyperledger-fabric - 在 Hyperledger Composer 中将资产拆分为两个资产。
- java - Android P:服务行为更改
- java - 对扩展抽象类的具体类的 Java 接口引用
- latex - 表中的乳胶 ACM 模板行颜色
- swift - “${PODS_ROOT}/SwiftLint/swiftlint”使用 Xcode 10 导致“Command PhaseScriptExecution failed with a nonzero exit code”