jQuery使从DOM中删除节点变得容易。但是如何从给定的jQuery对象中删除DOM元素呢?
jQuery使从DOM中删除节点变得容易。但是如何从给定的jQuery对象中删除DOM元素呢?
如果你想从jQuery对象中删除节点,请使用filter
或not
函数。更多信息请参见此处。
如何使用filter
:
var ps = $('p');
//Removes all elements from the set of matched elements that do
//not match the specified function.
ps = ps.filter(function() {
//return true to keep it, false to discard it
//the logic is up to you.
});
或者var ps = $('p');
//Removes all elements from the set of matched elements that
//do not match the specified expression(s).
ps = ps.filter('.selector');
如何使用 not
:
var ps = $('p');
//Removes elements matching the specified expression
//from the set of matched elements.
ps = ps.not('.selector');
如前所述,$.filter()
是过滤数据的绝佳选择。请注意,jQuery 对象可以像数组一样处理,因此,您可以在其上使用 splice()
等数组方法。
var people = $(".people");
people.splice(2,1); // Remove 1 item starting from index 2
.remove()
方法会将元素从页面中移除,同时删除任何相关的HTML、事件等(还有detach()
方法,它可以将元素从页面中移除,但仍然保留在内存中,并保留事件)。这个问题是关于如何保持jQuery元素,但将其从特定的jQuery对象中移除。 - user56reinstatemonica8<ul>
<li class="1" />
<li class="2" />
<li class="3" />
<li class="4" />
<li class="5" />
</ul>
筛选器遍历 jQuery 对象集合。对于每个元素:在 filter()
中返回 true
以保留 jQuery 对象集合中的当前项目。返回 false
以从 jQuery 对象集合中删除当前对象。
$("li").filter(function ()
{
if (this.className == "1" || this.className == "2") return true;
return false;
});
filter()
执行的匿名函数将返回对具有类1和/或2的列表项为真,从而从jQuery对象集合中删除最后三个列表项。
<ul>
<li class="1" />
<li class="2" />
<li class="3" />
<li class="4" />
<li class="5" />
</ul>
这段代码将一个类名("blue")添加到无序列表中。然后高亮显示前两个列表项。然后将点击处理程序附加到前两个列表项:
$(function ()
{
$("ul").addClass("blue").find("li").filter(function ()
{
if (this.className == "1" || this.className == "2") return true;
return false;
}).addClass("highlight").click(function ()
{
alert("I am highlighted!");
});
});