$(document).ready(function(){
var abc = false;
$(document).click(function(){
abc = true;
});
if (abc == true){
alert("ALERT");
//do some other things
}
});
有人帮忙吗?感谢
答案 0 :(得分:2)
这是由使用event model
的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>
答案 1 :(得分:1)
您的提醒无法启动,因为它不在点击处理程序中。它只在文档加载时执行一次并保持冷静。您应该在内部点击
移动您的检查$(document).click(function(){
abc = true;
if (abc == true){
alert("ALERT");
//do some other things
}
});
此外,对于布尔值,您可以直接在内部写入可变名称,如果条件好像期望一个布尔值
if (abc == true){
可缩短为
if (abc){
$(document).ready(function() {
var abc = false;
$(document).click(function() {
abc = true;
if (abc) {
alert("ALERT");
//do some other things
}
});
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
&#13;