我正在尝试一些基本的 Javascript 来选择元素和标签,但它给我带来了问题。 具体来说,我在使用 chrome 或 firefox 的开发工具中收到此错误:
未捕获类型错误:无法调用 null 的方法“getElementsByTagName”
奇怪的是,当我在浏览器的控制台中输入 javascript 命令时,它可以正常工作。 (选择包装器 div 中的 p 标签)
这是我的 html:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Test</title>
<link rel="stylesheet" href="default.css" />
<script type="text/javascript" src="selection.js"></script>
</head>
<body>
<div id="wrapper">
<p>Hello, this is a paragraph</p>
<p>Another one!</p>
<p>This is yet another paragraph</p>
</div>
</body>
</html>
那么我的 JavaScript 是:
window.onload = initP();
function initP() {
var para = document.getElementById('wrapper').getElementsByTagName('p');
}
最佳答案
尝试:
window.onload = initP;
而不是
window.onload = initP();
因为您正在调用该函数而不是分配它。
关于javascript - 无法调用 null 的方法 'getElementsByTagName',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20641420/