jQuery css选择器 - 选择所有但最后一个

时间:2012-08-19 08:21:52

标签: jquery css jquery-selectors

这是我的HTML:

<!-- Navigation -->
            <nav>
                <ul>
                    <li><a href="#">Products</a></li>
                    <li><a href="#">Gallery</a></li>
                    <li><a href="#">Guestbook</a></li>
                    <li><a href="#">Contacts</a></li>
                    <li><a href="#">Help</a></li>
                    <li><a id="cart" href="#"><span class="glyph general">2</span></a></li>
                </ul>
            </nav>

我想在除紫色背景的最后一个锚点以及id =“cart”红色背景的最后一个子节点上创建jQuery悬停效果,这里是我的jquery:

<script>
$(function () {
        $("nav ul li a:not(#cart)").hover(
            function (){
                $(this).hide().css("background-color","#6e0069").fadeIn(500);
            },
            function(){
                $(this).css("background-color","rgb(255,255,255)");
            }
        );
})

如何为红色背景的最后一个元素添加相同的功能?

1 个答案:

答案 0 :(得分:2)

不确定这是否是你所要求的,但我会这样做:

$("nav ul li a").hover(function() {
    var color = $(this).is("#cart") ? "rgb(255,0,0)" : "#6e0069"
    $(this).hide().css("background-color", color).fadeIn(500);
}, function() {
    $(this).css("background-color", "rgb(255,255,255)");
});​