问题
I basically want to know how global variables work in a javascript/JQuery environment. I am most familiar with a language called processing which I've been told is java-based. I expected variables in javascript and JQuery to behave like the ones in processing, but they do NOT work as I expect and I cannot for the life of me wrap my head around it.
I have a very simple example made up to illustrate my confusion:
var what="";
$(document).ready(function(){
$("p").click(function () {
what="p";
});
if(what=="p"){
alert(what);
}//end if
});//end doc ready
In processing, this would work because the 'what' variable is global and as it is changed by clicking on a paragraph, the if statement should be continuously checking to see if 'what'=='p', and trigger the alert. But that is not what happens-- 'what' only seems to be updated WITHIN the click function, even though it is a global variable, so when it comes to the if statement, 'what' still equals "" instead of "p".
If someone could explain why this happens, I will be very grateful!
回答1:
The if
statement only runs once when the DOM is first ready. It is not running continuously. If you want it to run during the click handler, then you would use this code:
var what="";
$(document).ready(function(){
$("p").click(function () {
what="p";
if(what=="p"){
alert(what);
}//end if
});
});//end doc ready
回答2:
the if statement should be continuously checking to see if 'what'=='p', and trigger the alert.
Why? None of your code produces that functionality. If you want that to happen, you can use setInterval()
:
setInterval(function() {
if(what=="p") {
alert("what");
}
}, 500); // executes function every 500 milliseconds
But that is not what happens-- 'what' only seems to be updated WITHIN the click function, even though it is a global variable
No, your what
variable is being updated globally. You just don't notice because you made false assumptions about the if
functionality (it's only being called once).
来源:https://stackoverflow.com/questions/12136050/how-do-global-variables-work-in-jquery-javascript-beginner-level