javascript 如何使用javascript删除段落的内容
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20926073/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to delete the contents of a paragraph with javascript
提问by James Dorfman
I have a paragraph that I'd like to delete the contents of.
我有一段我想删除其中的内容。
document.getElementById(id).innerHTML = "";
doesn't seem to be working. Does anyone have a better solution?
似乎没有工作。有没有人有更好的解决方案?
Here's an example
这是一个例子
<!DOCTYPE html>
<html>
<head>
<script>
document.getElementById("p").innerHTML = "";
</script>
</head>
<body>
<p id="p">
words
</p>
</body>
</html>
but the words in the paragraph are not removed. Thanks in advance to anyone that can help.
但段落中的词没有被删除。提前感谢任何可以提供帮助的人。
回答by Mihai Vilcu
<!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>
how to fix it ?
如何解决?
// only use this if you can't move your javascript at the bottom
window.onload = function() {
document.getElementById("p").innerHTML = "";
}
or move your javascript at the end of the page (this is the preferred one as javascript should always be loaded at the end of the page)
或将您的 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>
回答by Faron
I have often use jQuery for this function but, since you are seeking for pure javascript syntax. you will want to use this code:
我经常使用 jQuery 来实现这个功能,但是,因为您正在寻找纯 javascript 语法。您将要使用此代码:
document.getElementById("p").remove();
回答by Madhu VP
function funboi()
{
document.getElementById("p").innerHTML = "";
}
<!-- Just add a button. Works fine-->
<p id="p">
words are amazing
</p>
<button onclick="funboi()">click to delete</button>
回答by farvilain
Be aware you use something that's not in W3C spec... (removing by innerHTML='')
请注意,您使用的内容不在 W3C 规范中...(通过 innerHTML='' 删除)
var elem = document.getElementById(id);
if (!elem) {
console.log("No element for id:"+id);
} else {
elem.innerHTML="";
console.log("Should work");
}
回答by Rings
Make it a function and add with the body onload event it should work:
使它成为一个函数并添加主体 onload 事件,它应该可以工作:
<script>
function empty(){
document.getElementById("p").innerHTML = "";
}
</script>
<body onload='empty()'>
<p id="p">
words
</p>
</body>