javascript rollover effects question
I am learning JS currently with a js book. A rollover effects example got me, so I need some help.
I upload a snapshot on Flickr.com. The url is : http://www.flickr.com/photos/58745632@N05/5389380030/
The left side of the snapshot is the page and the right side of the snapshot is the javascript code. My question is can I change the content in the red box to the codes in the green box. If 开发者_开发知识库I can, why does the author bother to add this line "thisLink.imgToChange = thisImage"? And what is the relationship between "thisLink.imgToChange" and "thisImage"? Are they the same one or are they identical ones? Could someone explain it for me? Thank you very much.
thisImage
is the reference to an image object. It is being passed as a variable to the function.
An image object has properties like the source (.src), .width. height etc.
thisLink
is also an object, and it can have properites too. So, thisLink.imgToChange = thisImage
sets the "imgToChange" to the image fed into the function. imgToChange
is a completely arbitrary property chosen by the programmer. It's being used stash some data used later.
All this code demonstrates the "hard way" of doing a rollover. Having to type (or even use) "document.getElementById" over and over again all of this is a pain. Most of the time we depend on scripts to automate these things.
Frameworks, which are basically optimized versions of the type of code you're working on here, were developed to take care of the dirty work. The most popular framework, by far, is jQuery.
Doing pretty well the same thing using jQuery can be done in one line of code.
Here's another posting as an example.
Short answer:
.imgToChange
and thisImg
refer to the same place. .imgToChange
is added as a property so it's easy to use later, like in the onmouseout
function.
UPDATE
Regarding your comment: It won't work either way (probably).
Since setupRollover()
is called multiple times, the variable thisImage
will point to a different image node every time it's called. The code in the green box will only be applied to the most recent thisImage
.
The red box uses this
because that means "the object that fired the event". The red box sets up each object to refer to the appropriate image. Then, when this
is moused over, the correct image is changed.
Try it out yourself, it's easier to see than to explain.
Given that this is straight out of JavaScript & Ajax for the Web: Visual QuickStart Guide, 7th edition1, what in particular are you having trouble with in the (line-by-line) explanation on pages 96-97?
1 Co-written by me, btw.
精彩评论