如何编写JQuery代码,这将改变元素的顺序,如果'偶数'元素的某些类型是'。active'?我想把下一个(奇数)元素移到活动元素之前。我应该使用。index()和。detach()方法…
语法示例http://jsfiddle.net/Tymek/M6qFM/
<div id="wrap">
<div class="element">1. Pierwszy</div>
<div class="element">2. Drugi</div>
<div class="element">3. Trzeci</div>
<div class="element active">4. Czwarty</div> <!-- 4 is even -->
<div class="element">5. Piąty</div> <!-- then move this up -->
<div class="element">6. Szósty</div>
<div class="element">7. Siódmy</div>
</div>
您可以选择性地检查奇数索引项是否具有活动类,然后将以下项移动到奇数索引项之前。
// For each of the odd index elements
$('.element').filter(':odd').each(function(index, element) {
// If the element has the active class
if ($(element).hasClass('active')) {
// Get the next element and move it before the active element
$(element).next().insertBefore($(element));
}
});
当你有:odd
和:even
时,不需要检查索引(索引是零索引,所以在这种情况下你想检查:odd
)。
var $active = $(".active");
if ($active.is(":odd")) {
$active.next().after($active);
}
http://jsfiddle.net/M6qFM/1/