Whenever a user clicks on a link, or moves her cursor over one, JavaScript is sent a link event. One link event is called onClick, and it gets sent whenever someone clicks on a link. Another link event is called onMouseOver. This one gets sent when someone moves the cursor over the link.
You can use these events to affect what the user sees on a page. Here's an example of how to use link events. Try it out, view source, and we'll go over it line by line.
The first interesting thing is that there are no <script> tags. That's because anything that appears in the quotes of an onClick or an onMouseOver is automatically interpreted as JavaScript. In fact, because semicolons mark the end of statements allowing you to write entire JavaScripts in one line, you can fit an entire JavaScript program between the quotes of an onClick. It'd be ugly, but you could do it.
Here's the first line of interest: <a href="#" onClick="alert('Ooo, do it again!');">Click on me!</a>
This is just like a normal anchor tag, but it has the magic onClick="" element, which says, "When someone clicks on this link, run the little bit of JavaScript between my quotes." Notice, there's even a terminating semicolon at the end of the alert.
Also note that there's a # sign between the quotes in the href="#". This makes it so the browser doesn't try to load another Web page when you click on the link. If you put http://www.webmonkey.com/ in the href instead of the #, the browser would run the JavaScript in the onClick and the load up this here Webmonkey site.
Unfortunately, sometimes using the # sign causes the browser to jump to the top of the page when the link is clicked. To stop that from happening, change the link to this: <a href="#"onClick="alert('Ooo, do it again!');return false;">Click on me!</a>
Notice the return false; following the alert inside the onClick. This tells JavaScript to stop the browser from even looking at what's in the href. Because some very old browsers don't understand the return false, people usually do both things: Put the # inside the href and put return false inside the onClick. That makes sure all browsers do the right thing.
Here's the next line:
<a href="#" onMouseOver="alert('Hee hee!');">Mouse over me!</a>
This is just like the first line, but it uses an onMouseOver instead of an onClick.
本文地址:http://com.8s8s.com/it/it23514.htm