我有一个javascript函数'doAll',它应该写出所有放在<p>, </p>
标签之间的文本。在我的代码中,它以两种方式使用。
当我在页面末尾调用它时它可以正常工作。然而,当点击按钮事件发生时它也应该被触发。由于某种原因,它这次没有做它应该做的事情。当单击按钮时,它只会打印第一个<p>...</p>
html 元素的内部 html。
我的问题是为什么它在这两种情况下的工作方式不同,我应该怎么做才能解决这个问题。
<!DOCTYPE html>
<html>
<head>
<script>
function returnList(x)
{
return document.getElementsByTagName(x);
}
function writeList(x)
{
var i = 0;
while (x[i])
{
document.write(x[i++].innerHTML + '<br/>');
}
}
function doAll(x)
{
writeList(returnList(x));
}
</script>
</head>
<body>
<p>XXX</p>
<p>YYY</p>
<div style = 'background-color: gray;'>
<p>YYY</p>
<p>XXX</p>
</div>
<button type = 'button' onclick = "doAll('p')">
Click me!
</button>
<script>
document.write('<br/>');
doAll('p');
</script>
</body>
</html>
这是“输出”:
XXX
YYY
YYY
XXX
XXX
YYY
YYY
XXX
点击按钮后可以看到如下内容:
XXX