0

当我单击其中一个按钮时,<p>s仅在封装 div 中的所有按钮都应为黄色背景。
理想情况下,我希望在 jquery 选择器中查看和匹配元素选择器$(this)parent更新:抱歉,我没有明确提出我的要求。
我想查看父 div 的选择器、我想在父项中选择的元素以及$(this)所有在 select 子句中的元素。
假设您想从中获取<p>元素.left div,您可以像这样扩展选择器子句
$("p", ".left")- Gets all <p>in.left
在我的情况下,我想.left使用$(this), 而这个“是”按钮。应该在
$("p", $(this).closest("body > div"))

这是 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>
4

3 回答 3

4

您可以使用兄弟姐妹()而不是最接近全选<p>s。这是更新的小提琴

于 2013-05-06T02:16:44.320 回答
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/

于 2013-05-06T02:08:29.180 回答
0

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

更新了 jsFiddle

于 2013-05-06T21:51:09.047 回答