2013-07-09 128 views
1

即時通訊使用jquery向上或向下移動div,這是排名系統的一部分,所以我需要排名類保持不變,取決於div是第一,第二,第三等... 頂部的div應該總是有第一類,第二類等於第二等等等等等等。 任何幫助很多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()); 

    }); 
+0

你不擁有這些div的包裝/容器元素? –

+0

也許試試'var n = 1; $(「div」)。each(...; n + = 1;)'? –

+0

包裝元素有一類「contentContainer」 – user2563023

回答

-1

有asimpler純CSS的方法!
yoops,你可以這樣做:

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 
} 

我認爲這是比使用switchClass添加一些額外的計算到你的頁​​面

+0

這不完全是他要求的 –

+0

沒有必要直接操縱dom,我試圖展示最好的方式不是他想要的。我認爲這就是這個網站的地方! – Homam

+0

感謝Homam,你的建議奏效:D – user2563023

0

如果您正在使用jQuery UI,你可以做到這一點很簡單(但實現你自己的 「開關」 也不是那麼困難):

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(); 
});