日期:2014-05-16  浏览次数:20304 次

Pro JavaScript Techniques一处错误的代码

Pro JavaScript Techniques中文版256页的例子代码有误, 原版给出的例子就已经错误了
Listing A-30. Converting a Set of Links Into Plain URLs

// Convert all links to visible URLs (good for printing
// Find all <a> links in the document
var a = document.getElementsByTagName("a");
//首先这边循环不能用while, while ( a.length )只是判断a是否包含length属性, 在这边只要存在<a>元素,
//那么
document.getElementsByTagName("a") 返回一个NodeList, 即a, 同时这个NodeList包含length属性,
//这样将陷入死循环

while ( a.length ) {
? // Create a <strong> element
? var s = document.createElement("strong");
? // Make the contents equal to the <a> link URL
? // 因为用的while循环, 这边的i未定义
? s.appendChild( document.createTextNode( a[i].href ) );
? // Replace the original <a> with the new <strong> element
? // 这边的错误是replaceChild, 先不管i, 假设a[i]引用某个<a>元素
? // 那么这边的代码也应该是这么写的
a[i].parentNode.replaceChild( s, a[i] );
? a[i].replaceChild( s, a[i] );
}

以下是demo
<html>
<head>
</head>
<body>
<a href=" www.163.com ">163</a>
<a href=" www.sina.com ">新浪</a>
<script type="text/javascript">

? var a = document.getElementsByTagName( 'a');
? // 这是我修改后的代码
? for(var i=a.length-1;i>=0;i--){
? ??? var s = document.createElement(' strong');
? ??? s.appendChild(document. createTextNode(a[i].href))
? ??? a[i].parentNode.replaceChild( s, a[i]);
? }
?
? /**
? var a = document.getElementsByTagName("a");
while ( a.length ) {
? // Create a <strong> element
? var s = document.createElement("strong");
? // Make the contents equal to the <a> link URL
? s.appendChild( document.createTextNode( a[i].href ) );