jQuery防止删除类,如果第一个或最后一个孩子?

Nat*_*ers 3 jquery

我有一个“活动”类,并且经常被删除并添加到其他div中。但是我不希望将其应用于第一个或最后一个孩子...

JSFiddle:http : //jsfiddle.net/YuDDK/1/

HTML:

<div id="container">
<div class="item active"></div>
<div class="item"></div>
<div class="item"></div>
<div class="item"></div>
</div>
Run Code Online (Sandbox Code Playgroud)

JS:

$('#container').mousewheel(function(event, delta) {
    var active = $('.active');

    if (delta > 0) {
        if (active.not(":first-child")) {
            active.removeClass('active').prev().addClass('active');
        }

    } else {
        if (active.not(":last-child")) {
            active.removeClass('active').next().addClass('active');
        }
    }

    $(this).scrollTo( $('.active'),100);
    return false;
});
Run Code Online (Sandbox Code Playgroud)

und*_*ned 5

active.not(":first-child")返回一个jQuery对象,该对象始终为true,您可以使用ismethod来返回一个布尔值。

if ( !active.is(":first-child") )
Run Code Online (Sandbox Code Playgroud)