我有一个段落想要删除其内容。
document.getElementById(id).innerHTML = "";
似乎不起作用。有没有人有更好的解决方案?
这是一个例子
<!DOCTYPE html>
<html>
<head>
<script>
document.getElementById("p").innerHTML = "";
</script>
</head>
<body>
<p id="p">
words
</p>
</body>
</html>
但段落中的文字并未被删除。预先感谢任何可以提供帮助的人。
最佳答案
<!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>
如何解决?
// only use this if you can't move your javascript at the bottom
window.onload = function() {
document.getElementById("p").innerHTML = "";
}
或者将您的 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>
关于javascript - 如何用javascript删除段落内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20926073/