Reputation: 8509
OK guys this is intreting,
I'm testing this page
http://static.nemesisdesign.net/demos/ie8-strange/test.html
on IE8 / windows XP.
This is the code:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="content-language" content="en">
<title>Test</title>
</head>
<body>
<div id="thisgivesmeanerror">test</div>
<script>
thisgivesmeanerror = 'test';
alert('this alert won\'t be fired on my IE8, what about yours?');
</script>
</body>
</html>
If I open this page with IE8 I get an error. If I change the code of the script to:
<script>
// note that I added var prefix
var thisgivesmeanerror = 'test';
alert('this alert won\'t be fired on my IE8, what about yours?');
</script>
It works fine. This happens only on IE 7/8, didn't test it on IE6.
What do you think? Does it happen to you also? Or is it just my browser that has gone crazy?
You're saying that is just not using the var prefix that cause the error? I'm sorry guys but you're wrong, you didn't take time to test the code.
I uploaded a test2 page http://static.nemesisdesign.net/demos/ie8-strange/test2.html with the follwing cocde
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="content-language" content="en">
<title>Test 2</title>
</head>
<body>
<div id="thisgivesmeanerror">test</div>
<script>
thisdoesntgiveanyerror = 'test';
alert('This alert will be fired correcly');
</script>
</body>
</html>
That works fine.
So what is actually causing the error? The variable name without the var prefix having the same name as the ID of the DIV element.
Isn't this strange?
Upvotes: 0
Views: 376
Reputation: 101473
I'd say the JavaScript interpreter in IE is slightly stricter than on FireFox and others, meaning the script returns an error when it comes to the variable definition line. Putting var
in will ensure it actually is a variable.
It's very good practice to declare all your variables with var
James
EDIT
I can't get to IE at the moment, but I can recommend you change your <script>
tag to <script type="text/javascript">
.
Upvotes: 0
Reputation: 5358
use var
to declare variables instead of just plugging their name
Upvotes: 0
Reputation: 1038710
You should always precede your variable declarations with var
to specify their scope or you might observe inconsistent behavior between different browsers.
Upvotes: 1