Global variable does not want to change...

J

jimmy.dillies

Hello, I have a global variable which does not want to change :
<header>
....
<script type="text/javascript" language="JavaScript">
var i=1;
function swap()
{
var window.i = 1 - window.i ;
}
.....
</script>
....
<body>

<A href="" ... onclick="swap()"> <img src="pix/star.gif" > </A>

when clicking on 'star.gif', i does not change from 1 to 0 ...

Any clue ?
Thanks,
Jimmy
 
B

buhailiang

"(e-mail address removed) дµÀ£º
"
Hello, I have a global variable which does not want to change :
<header>
...
<script type="text/javascript" language="JavaScript">
var i=1;
function swap()
{
var window.i = 1 - window.i ;
~~~you reclaim the value, delete the "var" will be ok
 
L

Lich_Ray

Using global variable is not a good choose. Remenber global function is
always blind to global namespace. The best choose is, use "this.i"
instead of "window.i".
 
L

Lee

Lich_Ray said:
Using global variable is not a good choose. Remenber global function is
always blind to global namespace. The best choose is, use "this.i"
instead of "window.i".

If I understand you correctly, you're wrong.
functions have full access to global variables.
That's what "global" means:

<html>
<body>
<script type="text/javascript">
var globalVariable="Hello, world!";
function globalFunction() {
alert(globalVariable);
globalVariable="Goodbye";
}
globalFunction();
alert(globalVariable);
</script>
</body>
</html>


--
 
M

Michael Winter

(e-mail address removed) wrote:

[snip]
<script type="text/javascript" language="JavaScript">

The language attribute is deprecated and redundant. Omit it.
var i=1;
function swap()
{
var window.i = 1 - window.i ;

That is a syntax error: variable declarations consist of a comma
separated list of /identifiers/, with optional initialisers. The
character sequence, "window.i" is not an identifier.

function swap() {
i = 1 - i;
}

will do. You don't want a variable declaration within the function body:
that would make i a local variable.

[snip]

Mike
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,774
Messages
2,569,596
Members
45,142
Latest member
DewittMill
Top