I have this code in jQuery..
$(document).ready(function(){
var fieldCounter = 0; ...
I have a jQuery function that开发者_Python百科 increments this value.
This works, but I can't access this value on the page from a non-jQuery function? The reverse is also true, if I scope it in JavaScript e.g.
<script type="text/javascript">
var fieldCounter = 0;
I can access it from javascript but jQuery can't view it?
I'm probably doing something really dumb?
It has nothing to do with jQuery, but all with Javascript scope.
$(document).ready(function() {
var fieldCounter = 0;
});
fieldCounter
is declared inside a function
. Since Javascript has function scope, the variable is not visible outside the function.
BTW, jQuery is Javascript, they play by the same rules, they're not two different technologies.
Exhaustive answers can be found here: What is the scope of variables in JavaScript?
jQuery is not magic. It is a JavaScript library. Your issue is that you're defining a local variable inside a function. Due to the way JavaScript lexical scoping works, you can't access it outside that function (with the exception of closures, which does not apply here).
Most likely, you just want:
$(document).ready(function(){
fieldCounter = 0;
That will make it a global variable.
Edit: Note that using a namespace and/or declaring the global variable is cleaner, but not required.
Your problem in the first case is scope. By putting the var
init inside a function declaration, you've scoped it to access inside that function.
Something else is going on in the second case; more code would be necessary to see what.
The global scope in Javascript is window
. That means that when you declare variables directly in <script>
tags, you can get them back by asking for window.variableName
.
A common way to resolve these kinds of scoping issues is to create a namespace framework. If you do it right you can call myNamespace.subNamespace.variable
and have full confidence that because it's explicitly scoped to window
, you can get it back no matter where you are.
Remember that jQuery is built in Javascript. There's nothing special about it.
JavaScript has function scope.
var count = 8;
var myfunction = function() {
var newCount = count + 1;
};
alert(newCount); // undefined
it's because of the scope of javascript... try to read this
Variables declared inside jQuery code block will have local scope.If you need to access a variable both in local javascript function as well as jQuery code block then declare the variable at global level. Sample Code snippet :-
<script type="text/javascript" language="javascript">
var increment = 0;
$(document).ready(function() {
$("#button2").click(function() {
increment = increment + 1;
alert(increment);
});
});
function ClickMe() {
increment = increment + 1;
alert(increment);
}
</script>
精彩评论