开发者

Weird output with document.links.length

开发者 https://www.devze.com 2022-12-20 06:20 出处:网络
Save the following in a file (eg. file.htm) and it works => prints out \"3\". But if I uncomment the line \'document.write(\"Hello: \");\' it doesn\'t work anymore (prints out \"0\"). Anyone knows why

Save the following in a file (eg. file.htm) and it works => prints out "3". But if I uncomment the line 'document.write("Hello: ");' it doesn't work anymore (prints out "0"). Anyone knows why?

<html>
<head>
<script language="JavaScript" type="text/javascript">
function display() {
    //document.write("Hello: ");
    document.write(document.links.length + "<br>");
}
</script>
</head>
<body onload="display()">

<A href="link0.htm">Link 0</A>
<A href="link1.htm">Link 1<开发者_运维问答;/A>
<A href="link2.htm">Link 2</A>

</body>
</html>


In Chrome I observe this behaviour, and most other browsers probably too. The reason is as follows:

Without the first document.write, it works as expected. Nothing special here.

But when you include the first document.write it overwrites the entire contents of the document, so then there aren't any links left. The second document.write reports correctly that there are 0 links in the document.


First, don't use document.write() to "display" your output. If this is just a test, use the alert() method. document.write() is only supposed to be used while the page is loading. Once the stream is closed and the document is loaded, document.write() will have unpredictable results.

Second, instead of using document.links, try using document.getElementsByTagName("A"). That will give you an array of all the anchor tags in the document.


Because when you call document.write the first time, it removes all links from the DOM. It replaces the entire innerHTML of document.body with "Hello: ".

You should never use document.write anyway.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号