我有一个列表,我只想从其中删除所有子 node .使用jQuery最有效的方式是什么?这就是我所拥有的:

<ul id='foo'>
  <li>a</li>
  <li>b</li>
</ul>

var thelist = document.getElementById("foo");   
while (thelist.hasChildNodes()){
    thelist.removeChild(thelist.lastChild);
}

is there a shortcut rather than removing each item, one at a time?

----------- Edit ----------------

每个列表元素都附加了一些数据,还有一个如下的点击处理程序:

$('#foo').delegate('li', 'click', function() {
    alert('hi!');
});

// adds element to the list at runtime
function addListElement() {
    var element = $('<li>hi</hi>');
    element.data('grade', new Grade());
}

最后,我可能还会 for each 列表项添加按钮——所以看起来空()是确保没有内存泄漏的方法吗?

推荐答案

You can use .empty(), like this:

$("#foo").empty();

From the docs:

从DOM中删除匹配元素集的所有子 node .

Jquery相关问答推荐

JQuery DateTimePicker-在 Select 中抓取星期几

如何定位 prism.js 脚本中包含的代码?

jQuery在localStorage时将类添加到正文

jQuery:使用变量作为 Select 器

jQuery中的正则表达式字段验证

使用 jQuery 按文本内容 Select 选项

jQuery: Select 属性大于值的所有元素

可以在不使用for=id的情况下将标签与复选框相关联吗?

如何在不导致页面滚动的情况下删除位置哈希?

jQuery切换文本?

如何使所有浏览器都支持 ?有什么 Select 吗?

offsetTop 与 jQuery.offset().top

jQuery 不会从 AJAX 查询中解析我的 JSON

是否可以在 beforeunload 弹出窗口中显示自定义消息?

使用 JQuery 激活 bootstrap 选项卡

在jquery中查找具有某个属性值的所有元素

订单对象是否由指定的 jQuery Select 器返回?

获取jQuery中下拉列表的值

如何插入元素作为第一个子元素?

一起使用 JQuery-Mobile/Phonegap 的正确方法?