2017-05-30 63 views
-1

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](一個數組)。即爲什麼我想刪除該循環。 –

回答

0

你有一個額外的「}」,使你的代碼失敗。

} 
    // ]]> 
</script> 

腳本區域

相關問題