PDA

View Full Version : A real paradox!


ConfusedOfLife
09-10-2002, 11:48 PM
Look at this code ( you probably need to run it! )

<html>
<head>
<title>Untitled</title>
<style>
div
{
width : 90px;
cursor : default;
}
</style>
<script>
divs = ["1", "2", "3", "4", "kk"];
function showID(which)
{
alert(which);
}
function init()
{
for (i=0; i<divs.length; i++)
document.getElementById(divs[i]).onmouseover = function() { setTimeout("showID(" + this.id + ")",1000); }
}
</script>
</head>
<body onload="init()">

<div id="1">
It's a test!
</div>

<div id="2">
It's a test!
</div>

<div id="3">
It's a test!
</div>

<div id="4">
It's a test!
</div>

<div id="kk">
It's a test!
</div>

</body>
</html>



Move the mouse on the titles, as you can see through the code, by passing each div, you'll see an alert box after one second
showing the id of that div, it's true for all of them, except the last one, that's id is not a number, but instead a string, i.e
"kk", so, what's the reason that it shows "[object]" in the alert box?!
I solved this by re-writing the showID function in this way:

function showID(which)
{
if ( which.id != null )
alert(which.id)
else
alert(which);
}

But I still don't know why it behaves so wierd!

Owl
09-11-2002, 01:56 AM
Hi ConfusedOfLife,

The outcome of: setTimeout("showID(" + this.id + ")"...

is:

showID(1)
showID(2)
showID(3)
showID(4)
showID(kk)

To realise that, add alert(typeof which) inside showID.
You must have checked it with IE, Gecko would throw "undefined" for the kk.

The correct way to write the setTime would be:

setTimeout("showID('" + this.id + "')"...

( •) (• )
>>V

ConfusedOfLife
09-11-2002, 11:29 PM
Thanks! I used alert, but I couldn't find out what's going on! I mean I got "kk", but I just said if it's like this with "kk", then it's the same for all of them! It seems that's different!