Jam*_*man 1 html javascript getelementbyid
我有一个段落想要删除其内容。
document.getElementById(id).innerHTML = "";
Run Code Online (Sandbox Code Playgroud)
似乎不起作用。有人有更好的解决方案吗?
这是一个例子
<!DOCTYPE html>
<html>
<head>
<script>
document.getElementById("p").innerHTML = "";
</script>
</head>
<body>
<p id="p">
words
</p>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)
但该段中的文字并没有被删除。预先感谢任何可以提供帮助的人。
<!DOCTYPE html>
<html>
<head>
<!-- here the p tag doesn't exist yet -->
<script>
document.getElementById("p").innerHTML = "";
</script>
</head>
<body>
<p id="p">
words
</p>
<!-- however here it does exist -->
</body>
</html>
Run Code Online (Sandbox Code Playgroud)
如何修复它?
// only use this if you can't move your javascript at the bottom
window.onload = function() {
document.getElementById("p").innerHTML = "";
}
Run Code Online (Sandbox Code Playgroud)
或者将您的 javascript 移至页面末尾(这是首选方法,因为 javascript 应始终在页面末尾加载)
<!DOCTYPE html>
<html>
<head>
<!-- here the p tag doesn't exist yet -->
</head>
<body>
<p id="p">
words
</p>
<!-- however here it does exist -->
<script>
document.getElementById("p").innerHTML = "";
</script>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
21464 次 |
| 最近记录: |