从jQuery对象中删除项目

Wil*_*avy 49 jquery

jQuery可以轻松地从DOM中删除节点.但是你如何从jQuery对象中删除一些东西?

geo*_*wa4 55

如果您正在讨论从jQuery对象中删除节点,请使用filternot函数.请看这里了解更多.

使用方法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.
});
Run Code Online (Sandbox Code Playgroud)

要么

var ps = $('p');

//Removes all elements from the set of matched elements that 
//do not match the specified expression(s).
ps = ps.filter('.selector');
Run Code Online (Sandbox Code Playgroud)

使用方法not:

var ps = $('p');

//Removes elements matching the specified expression 
//from the set of matched elements.
ps = ps.not('.selector'); 
Run Code Online (Sandbox Code Playgroud)

  • 绊倒我的一件事是除非你重新分配,它实际上不会从缓存的选择器中删除任何东西.所以你需要ps = ps.filter(function(){// stuff}); (8认同)

Sam*_*son 8

如前所述$.filter(),过滤数据是一个很好的选择.另请注意,jQuery对象可以像数组一样处理,因此,您可以使用类似的数组方法splice().

var people = $(".people");
people.splice(2,1); // Remove 1 item starting from index 2
Run Code Online (Sandbox Code Playgroud)


cll*_*pse 3

<ul>
    <li class="1" />
    <li class="2" />
    <li class="3" />
    <li class="4" />
    <li class="5" />
</ul>
Run Code Online (Sandbox Code Playgroud)

Filter 迭代 jQuery 对象集合。对于每个元素: 返回trueinsidefilter()以将当前项保留在 jQuery 对象集合中。返回false以从 jQuery 对象集合中删除当前对象。

$("li").filter(function ()
{
    if (this.className == "1" || this.className == "2") return true;

    return false;
});
Run Code Online (Sandbox Code Playgroud)

在这种情况下; 执行的匿名函数将为具有类1和/或2filter()的列表项返回 true ,进而从 jQuery 对象集合中删除最后三个列表项。 一个实际的例子:


<ul>
    <li class="1" />
    <li class="2" />
    <li class="3" />
    <li class="4" />
    <li class="5" />
</ul>
Run Code Online (Sandbox Code Playgroud)

此代码片段将一个类(“蓝色”)添加到无序列表中。然后突出显示前两个列表项。然后将点击处理程序附加到前两个列表项:

$(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!");
    });
});
Run Code Online (Sandbox Code Playgroud)