[英]Changing boolean value on document click
對不起這個非常基本的問題,但它讓我發瘋,我不明白什么不能解決這個非常簡單的Jquery代碼。 我只想在點擊我的文檔時將我的“abc”布爾值從false更改為true,並在“abc”為真時啟動警報(僅用於示例)。
$(document).ready(function(){
var abc = false;
$(document).click(function(){
abc = true;
});
if (abc == true){
alert("ALERT");
//do some other things
}
});
有人幫忙嗎? 謝謝
這是由使用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
語句放在click處理程序中,它就能正常工作。
$(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 (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>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.