[英]Javascript: setting variable to nodeValue not working
我在设置变量时遇到麻烦,找不到任何有用的文档。
这有效:
<!DOCTYPE html>
<html>
<body onload="alert(document.getElementById('foo').firstChild.nodeValue)">
<a id="foo" href="old">Foobar</a>
</body>
</html>
但这不起作用:
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
var theText = document.getElementById('foo').firstChild.nodeValue ;
</script>
</head>
<body onload="alert(theText)">
<a id="foo" href="old">Foobar</a>
</body>
</html>
警报显示“未定义”。 我真正想要做的是这样的事情,它也不起作用:
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
var theElement = document.getElementById('foo') ;
var theText = theElement.firstChild.nodeValue ;
document.write(theElement.getAttribute('href')) ;
theElement.setAttribute('href', theText) ;
document.write(meta.getAttribute('href')) ;
</script>
</head>
<body>
<a id="foo" href="old">Foobar</a>
</body>
</html>
为什么这不起作用?
当脚本运行时, foo
元素不存在。 如果您检查JavaScript控制台,则应该看到如下错误:
未捕获的TypeError:无法读取null的属性“ firstChild”
您会收到此错误,因为如果找不到要查找的元素,则getElementById
将返回null
。
您需要在标记后执行JavaScript代码。 将您的script
标签移到body
的底部,或将其放在DOM ready / load事件处理程序中。 例如:
<body onload="alert(theText)">
<a id="foo" href="old">Foobar</a>
<!-- Now the `foo` element actually exists, our script can find it -->
<script type="text/javascript">
var theText = document.getElementById('foo').firstChild.nodeValue;
</script>
</body>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.