对不起这个非常基本的问题,但这让我很疯狂,我不明白这个非常简单的 Jquery 代码上有什么不起作用。 我只想在单击我的文档时将我的"abc"布尔值从 false 更改为 true,并在"abc"为 true 时发出警报(仅供示例使用(。
$(document).ready(function(){
var abc = false;
$(document).click(function(){
abc = true;
});
if (abc == true){
alert("ALERT");
//do some other things
}
});
有人帮忙吗?谢谢
这是由JavaScript使用event model
引起的。这是您的一段代码,其中包含详细说明:
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>
警报不会启动,因为它不在点击处理程序中。它仅在文档加载时执行一次并保持平静。您应该将检查移至单击内
$(document).click(function(){
abc = true;
if (abc == true){
alert("ALERT");
//do some other things
}
});
此外,对于布尔值,您可以直接在 if 条件中写入变量名称,就好像无论如何都期望一个布尔值
一样if (abc == true){
可以缩短为
if (abc){
所以,在把你所有的碎片放在一起之后,
$(document).ready(function() {
var abc = false;
$(document).click(function() {
abc = true;
if (abc) {
alert("ALERT");
//do some other things
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>