代码之家  ›  专栏  ›  技术社区  ›  Will Peavy

从jquery对象中移除项

  •  47
  • Will Peavy  · 技术社区  · 15 年前

    jquery使从DOM中删除节点变得容易。但是如何从jquery对象中删除某些内容呢?

    3 回复  |  直到 8 年前
        1
  •  53
  •   geowa4    14 年前

    如果要从jquery对象中删除节点,请使用 filter not 功能。 See here for more .

    如何使用 滤波器 :

    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');
    

    如何使用 :

    var ps = $('p');
    
    //Removes elements matching the specified expression 
    //from the set of matched elements.
    ps = ps.not('.selector'); 
    
        2
  •  8
  •   Mosh Feu Alex Chen    8 年前

    如前所述, $.filter() 是过滤数据的好选择。还要注意 the jQuery object can be handled like an array ,因此,可以使用数组方法,例如 splice() 关于它。

    var people = $(".people");
    people.splice(2,1); // Remove 1 item starting from index 2
    
        3
  •  2
  •   cllpse    15 年前
    <ul>
        <li class="1" />
        <li class="2" />
        <li class="3" />
        <li class="4" />
        <li class="5" />
    </ul>
    

    过滤器迭代jquery对象集合。对于每个元素:返回 true 里面 filter() 保留jquery对象集合中的当前项。返回 false 从jquery对象集合中移除当前对象。

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

    在这种情况下,匿名函数由 过滤器() 将为具有类的列表项返回true 和/或 ,然后从jquery对象集合中移除最后三个列表项。


    一个实际例子:

    <UL & GT;
    <li class=“1”/>
    <li class=“2”/>
    <li class=“3”/>
    <li class=“4”/>
    <li class=“5”/>
    &L/UL & GT;
    

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

    $(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!");
        });
    });