Java Reference
In-Depth Information
Handling Events via Object Properties
Now let's look at the second way to connect to events.
With this method, you fi rst need to defi ne the function that will be executed when the event occurs.
Then you need to set that object's event handler property to the function you defi ned.
This is illustrated in the following example:
<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Strict//EN”
“http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd”>
<html xmlns=”http://www.w3.org/1999/xhtml”>
<head>
<title>Chapter 6: Example 4</title>
</head>
<body>
<script type=”text/javascript”>
function linkSomePage_onclick()
{
alert('This link is going nowhere');
return false;
}
</script>
<a href=”somepage.htm” name=”linkSomePage”>
Click Me
</a>
<script type=”text/javaScript”>
window.document.links[0].onclick = linkSomePage_onclick;
</script>
</body>
</html>
Save this as ch6_examp4.htm.
You defi ne the function linkSomePage_onclick(), much as you did previously. As before, you can
return a value indicating whether you want the normal action of that object to happen.
Next you have the <a/> element, whose object's event you are connecting to. You'll notice there is no
mention of the event handler or the function within the attributes of the tag.
The connection is made between the object's event and the function on the fi nal lines of script, as
shown in the following code:
<script type=”text/javaScript”>
document.links[0].onclick = linkSomePage_onclick;
</script>
As you saw before, document.links[0] returns the a object corresponding to the fi rst link in your
web page, which is your linkSomePage hyperlink. You set this object's onclick property to reference
your function — this makes the connection between the object's event handler and your function. Note
that no parentheses are added after the function name. Now whenever you click the link, your function
gets executed.
Search WWH ::




Custom Search