我正在学习 HTML、CSS 和 JavaScript。现在我想在 <p>
标签中写文档标题,我写了这个 HTML 文件:
<!DOCTYPE html>
<html>
<head>
<title>HTML experimentation</title>
<script>
document.getElementById("document_title").innerHTML = document.title;
</script>
</head>
<body>
<p id="document_title">This text should be replaced by the title of the document</p>
</body>
</html>
根据我在网上找到的教程,这应该有效。它不是。为什么?
我注意到如果我这样做:
<!DOCTYPE html>
<html>
<head>
<title>HTML experimentation</title>
<meta charset="utf-8">
<script type="text/javascript"
src="https://cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML">
</script>
<script type="text/x-mathjax-config">
MathJax.Hub.Config({
tex2jax: {
inlineMath: [ ['$','$'], ["\\(","\\)"] ],
processEscapes: true
}
});
document.getElementById("document_title").innerHTML = document.title;
</script>
</head>
<body>
<p id="document_title">This text should be replaced by the title of the document</p>
</body>
</html>
它有效。然而,这似乎不是我想要的方式。
答案 0 :(得分:-1)
执行脚本时 p
标记尚未加载。
script
标记应始终位于 </body>
结束标记之前或之后。
<!DOCTYPE html>
<html>
<head>
<title>HTML experimentation</title>
</head>
<body>
<p id="document_title">This text should be replaced by the title of the document</p>
<script>
document.getElementById("document_title").innerHTML = document.title;
</script>
</body>
</html>
一些有用的资源