我想删除第二个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 :(得分:0)
你有额外的&#34;}&#34;这使你的代码失败。
}
// ]]>
</script>
脚本区域结束前的最后一个