Just a small problem regarding javscript BOM question
- by caramel1991
The question is this:
Create a page with a number of links. Then write code that fires on the window onload event, displaying
the href of each of the links on the page.
And this is my solution
<html>
<body language="Javascript" onload="displayLink()">
<a href="http://www.google.com/">First link</a>
<a href="http://www.yahoo.com/">Second link</a>
<a href="http://www.msn.com/">Third link</a>
<script type="text/javascript" language="Javascript">
function displayLink()
{
for(var i = 0;document.links[i];i++)
{
alert(document.links[i].href);
}
}
</script>
</body>
</html>
This is the answer provided by the book
<html>
<head>
<script language=”JavaScript” 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>
Before I get into the javascript tutorial on how to check user browser version or model,I was using the same method as the example,by acessing the length property of the links array for the loop,but after I read through the tutorial,I find out that I can also use this alternative ways,by using the method that the test condition will evalute to true only if the document.links[i] return a valid value,so does my code is written using the valid method??If it's not,any comment regarding how to write a better code??Correct me if I'm wrong,I heard some of the people say "a good code is not evaluate solely on whether it works or not,but in terms of speed,the ability to comprehend the code,and could posssibly let others to understand the code easily".Is is true??