1

Im using jquery to move divs either up or down, which is part of a ranking system, so I need the ranking classes to stay the same depending on whether the div is either first, second, third and so on... The top div should always have class first, second div class equals second etc etc... Any help much appr.

html:

<div class="top5 first">
    <div class="voter">
        <a class="up" href="#">up</a>
        <a class="down" href="#">down</a>
    </div>                    
</div>


<div class="top5 second">
    <div class="voter">
        <a class="up" href="#">up</a>
        <a class="down" href="#">down</a>
    </div>                    
</div>

<div class="top5 third">
    <div class="voter">
        <a class="up" href="#">up</a>
        <a class="down" href="#">down</a>
    </div>                    
</div>

jquery:

 $('.up').click(function() {
        var parent = $(this).parent().parent();
        parent.insertBefore(parent.prev());

    });
    $('.down').click(function() {
        var parent = $(this).parent().parent();
        parent.insertAfter(parent.next());

    });
4

2 回答 2

0

如果您使用的是 jQuery UI,您可以使用switchClass(但实现您自己的“开关”并不难):

http://jsfiddle.net/vvBuF/2/

var classes = ['first', 'second', 'third'];
function switchClasses(elem1, elem2) {
    if(!elem1 || elem1.length === 0 || 
       !elem2 || elem2.length === 0) { return; }
    var from = '';
    var to = '';
    $.each(classes, function(i, e){if(elem1.hasClass(e)) {from=e;}});
    $.each(classes, function(i, e){if(elem2.hasClass(e)) {to=e;}});
    switchClass(elem1, from, to);
    switchClass(elem2, to, from);
}

function switchClass(elem, from, to) {
    elem.removeClass(from);
    elem.addClass(to);
}

$('.up').click(function() {
    var parent = $(this).parent().parent();
    var prev = parent.prev();
    parent.insertBefore(prev);
    switchClasses(parent, prev);
});
$('.down').click(function() {
    var parent = $(this).parent().parent();
    var next = parent.next();
    parent.insertAfter(next);
    switchClasses(parent, next);
});

或者你可以recalculate从下往上:

http://jsfiddle.net/7fkbf/

var classes = ['first', 'second', 'third'];
function recalculate() {
    $('.top5').each(function(index) {
        var t = $(this);
        $.each(classes, function(i,e) {t.removeClass(e);});
        t.addClass(classes[index]);
    });
}


$('.up').click(function() {
    var parent = $(this).parent().parent();
    var prev = parent.prev();
    parent.insertBefore(prev);
    recalculate();
});
$('.down').click(function() {
    var parent = $(this).parent().parent();
    var next = parent.next();
    parent.insertAfter(next);
    recalculate();
});
于 2013-07-09T05:11:57.247 回答
-1

有更简单的纯 css 方法!
哎呀,你可以这样做:

some-parent div:nth-child(0){
    do css
}  
some-parent div:nth-child(1){
    do another css
}  
some-parent div:nth-child(2){
    do another css
}  

我认为这比在页面中添加一些额外的计算要简单得多

于 2013-07-09T04:45:10.517 回答