Java Reference
In-Depth Information
<head>
<title>Chapter 6: Question 1</title>
<script type=”text/javascript”>
function displayLinks()
{
var linksCounter;
for (linksCounter = 0; linksCounter < document.links.length;
linksCounter++)
{
alert(document.links[linksCounter].href);
}
}
</script>
</head>
<body onload=”displayLinks()”>
<a href=”link0.htm” >Link 0</a>
<a href=”link1.htm”>Link 2</a>
<a href=”link2.htm”>Link 2</a>
</body>
</html>
Save this as ch06_q1.htm .
You connect to the window object's onload event handler by adding an attribute to the opening
<body> tag.
<body onload=”displayLinks()”>
On the onload event fi ring, this will run the script in quotes calling the displayLinks() function.
In this function you use a for loop to cycle through each a object in the document object's links
collection.
function displayLinks()
{
var linksCounter
for (linksCounter = 0; linksCounter < document.links.length; linksCounter++)
{
alert(document.links[linksCounter].href);
}
}
You used the length property of the links collection in your condition to determine how many times
you need to loop. Then, using an alert box, you display each a object's href property. You can't use
document.write() in the load event because it occurs when the page has fi nished loading.
Search WWH ::




Custom Search