可以我们改变或删除该for循环(J = 0;Ĵ<第[I] .childNodes.length; J ++)

问题描述:

for reference purpose可以我们改变或删除该for循环(J = 0;Ĵ<第[I] .childNodes.length; J ++)

我想删除第二个for循环和,而不是使用childNodes[j],我想去与.firstChild

<!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" xml:lang="en" lang="en"> 
    <head> 
    <title>My Web Page</title> 
    <script type="text/javascript"> 
     // <![CDATA[ 
     function displayParas() { 
      var output = ""; 
      var paras = document.getElementsByTagName("p"); 

      for (i=0; i < paras.length; i++) { 
      for (j=0; j < paras[i].childNodes.length; j++) { 
       if (paras[i].childNodes[j].nodeType == Node.TEXT_NODE) { 
       output += paras[i].childNodes[j].nodeValue + "\n"; 
       } 
      } 
      } 

      alert(output); 
     } 
     // ]]> 
    </script> 
    </head> 
    <body> 
    <h1>The Widget Company</h1> 

我的程序:

<!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" xml:lang="en" lang="en"> 
    <head> 
    <title>My Web Page</title> 
    <script type="text/javascript"> 
     // <![CDATA[ 
     function displayParas() { 
      var output = ""; 
      var paras = document.getElementsByTagName("p"); 

      for (i=0; i < paras.length; i++) { 
      if (paras[i].firstChild.nodeType == Node.TEXT_NODE) { 
       output += paras[i].firstChild.nodeValue + "\n"; 
       } 
       else{ 
        document.write(paras[i].firstChild.firstChild.nodeValue); 
       } 
      } 
       alert(output); 
      } 


     } 
     // ]]> 
    </script> 
    </head> 
    <body> 
    <h1>The Widget Company</h1> 
    <p>Welcome to the Widget Company!</p> 
    <p>We have lots of fantastic widgets for sale.</p> 
    <p>Feel free to browse!</p> 
    <p><a href="javascript:displayParas()">Display paragraph text</a></p> 
    </body> 
</html> 

我的输出应该是这样的:

Welcome to the Widget Company! 

We have lots of fantastic widgets for sale. 

Feel free to browse! 

Display paragraph text 

但是在第二个代码中,当我点击超链接时什么也没有发生。

+0

井是第一个孩子你认为这是结束前的最后一个? 'console.log(paras [i] .firstChild)' – epascarello

+0

并且有人可以解释为什么当paras [i] .firstChild只有一个值时,我应该使用childNodes [j](一个数组)。即为什么我想删除该循环。 –

你有一个额外的“}”,使你的代码失败。

} 
    // ]]> 
</script> 

脚本区域