很抱歉这个非常基本的问题,但它让我发疯,我不明白这个非常简单的 Jquery 代码有什么问题。 我只想在单击我的文档时将我的“abc” boolean 值从 false 更改为 true,并在“abc”为真时启动警报(仅作为示例)。
$(document).ready(function(){
var abc = false;
$(document).click(function(){
abc = true;
});
if (abc == true){
alert("ALERT");
//do some other things
}
});
有人帮忙吗?谢谢
最佳答案
这是由 JavaScript 使用事件模型
引起的。这是你的一段代码,有详细的解释:
var abc = false;
$(document).click(function() {
// Note that this function is attached to the `click` event
// It will be triggered only when the `click` event is triggered
// This means that the code inside it is not executed at the moment
abc = true;
});
// abc is false at the moment so the if statement won't execute
if (abc == true) {
alert("ALERT");
//do some other things
}
要解决这个问题,只需将 if
语句放在点击处理程序中,它就会正常工作。
$(document).ready(function() {
var abc = false;
$(document).click(function(){
abc = true;
if (abc == true){
alert("ALERT");
//do some other things
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
关于javascript - 单击文档更改 boolean 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45737194/