如何使用 JavaScript 清除 div 的内容?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3450593/
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 do I clear the content of a div using JavaScript?
提问by Rajasekar
When the user clicks a button on my page, the content of a div should be cleared. How would I go about accomplishing this?
当用户单击我页面上的按钮时,应该清除 div 的内容。我将如何实现这一目标?
回答by Tom Gullen
Just Javascript (as requested)
只是 Javascript(根据要求)
Add this function somewhere on your page (preferably in the <head>)
在您的页面上的某处添加此功能(最好在<head>)
function clearBox(elementID)
{
document.getElementById(elementID).innerHTML = "";
}
Then add the button on click event:
然后在点击事件上添加按钮:
<button onclick="clearBox('cart_item')" />
In JQuery (for reference)
在 JQuery 中(供参考)
If you prefer JQuery you could do:
如果你更喜欢 JQuery,你可以这样做:
$("#cart_item").html("");
回答by Mic
You can do it the DOM way as well:
你也可以用 DOM 方式来做:
var div = document.getElementById('cart_item');
while(div.firstChild){
div.removeChild(div.firstChild);
}

