【问题标题】:jQuery - toggle the class of a parent element?jQuery - 切换父元素的类?
【发布时间】:2010-04-18 13:38:17
【问题描述】:

我有几个列表元素,像这样:

<li class="item">
    <a class="toggle"><h4>ämne<small>2010-04-17 kl 12:54 by <u>nike1</u></small></h4></a>
    <div class="meddel">
        <span>
            <img style="max-width: 70%; min-height: 70%;" src="profile-images/nike1.jpg" alt="" />
            <a href="account.php?usr=47">nike1</a>
        </span>

        <p>text</p>
        <span style="clear: both; display: block;"></span>
    </div>
</li>

<li class="item odd">
    <a class="toggle"><h4>test<small>2010-04-17 kl 15:01 by <u>nike1</u></small></h4></a>
    <div class="meddel">
        <span>
            <img style="max-width: 70%; min-height: 70%;" src="profile-images/nike1.jpg" alt="" />
            <a href="account.php?usr=47">nike1</a>
        </span>

        <p>test meddelande :) [a]http://youtube.com[/a]</p>
        <span style="clear: both; display: block;"></span>
    </div>
</li>

我正试图弄清楚如何做到这一点,以便当您单击带有类 .toggle 的链接时,父元素(li 元素)将切换类 .current。

我不确定以下代码是否正确,但它不起作用。

$(this).parent('.item').toggleClass('.current', addOrRemove);

即使我删除“('.item')”,它似乎也没有任何区别。

那么,有什么想法吗?

提前致谢

【问题讨论】:

    标签: jquery class toggle parent


    【解决方案1】:

    toggleClass 采用类名,而不是选择器。因此,您不应包含.
    将其更改为toggleClass('current')(没有.)。

    此外,您可以通过调用closest 而不是parent 使您的代码更加健壮。 closest 将搜索与选择器匹配的最里面的父元素,因此如果链接嵌套在 .item 内,它将继续工作。

    【讨论】:

    • 谢谢,但似乎仍然无法正常工作:/ $('.pmlist ul li .toggle').click(function() { $(this).next("div" ).toggle(250); $(this).closest('item').toggleClass('current'); });触发之前的切换功能,只是切换类功能由于某种原因不起作用。
    • 你不能将代码块作为 cmets 发布,甚至添加新行,这有点糟糕:S 希望你无论如何都能阅读它:P
    • 你能在 Firebug 中看到这个类吗?
    • 尝试console.log($(this).parent('.item'))检查选择器是否匹配。
    • @Nike - .closest() 使用选择器,所以它确实需要.item 中的.,所以你的代码应该是:$('.pmlist ul li .toggle').click(function() { $(this).next("div").toggle(250); $(this).closest('.item').toggleClass('current'); });
    猜你喜欢
    • 2010-11-01
    • 1970-01-01
    • 2011-02-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-12-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多