获取最近父级中的所有匹配元素

时间:2013-05-06 02:05:02

标签: jquery jquery-selectors

当我点击其中一个按钮时,只有封装div中的所有<p>s都应该被赋予黄色背景。
理想情况下,我希望在jquery选择器中看到$(this)parent和匹配元素选择器。 更新:对不起,我没有明确要求。
我想看看父div的选择器,我想在父级中选择的元素,以及select子句中的$(this) all。 假设您想从<p>获取.left div元素,您可以像这样扩展选择子句 $("p", ".left") - 获取<p>中的所有.left 在我的情况下,我希望使用.left来抓住$(this),而这是“是”按钮。 应该在行中 $("p", $(this).closest("body > div"))

Heres the jsFiddle
码。

    <style>
    div p.painted {
        background-color: #FF0;
    }
    </style>
    <div class="left">
        <div class="actions">
            <div class="ui">
                <div class="colors">
                    <button class="paint">Paint it yellow!</button>
                </div>
            </div>
        </div>
        <p>
            Lorem Ipsum 
        </p>
        <p>
            Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.
        </p>
    </div>
    <div class="right">
        <div class="actions">
            <div class="ui">
                <div class="colors">
                    <button class="paint">Paint it yellow!</button>
                </div>
            </div>
        </div>
        <p>
            Lorem Ipsum 
        </p>
        <p>
            Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.
        </p>
    </div>

    <script>
    $(function(){
        $(".paint").click(PaintIt);
    });

    function PaintIt(){
        $(this).closest("p").addClass("painted");
    }
    </script>

3 个答案:

答案 0 :(得分:4)

您可以使用siblings()代替最近选择所有<p>s。这是更新的fiddle

答案 1 :(得分:1)

closest根据您的标记选择所选元素中最接近的父元素,首先应选择父元素,然后选择/查找段落元素。

$(this).closest("div").siblings('p').addClass("painted");

或:

$(this.parentNode).siblings('p').toggleClass("painted");

或:

$(this.parentNode).closest('div').find('p').toggleClass("painted");

http://jsfiddle.net/nKPFv/

答案 2 :(得分:0)

实际上这很有效 $("p", $(this).closest("body > div"))
不知道为什么它在测试时没有!

Updated jsFiddle