Question

I have a list of items. Some number of items at the top have a class.

<ul>
    <li class="blue moveMeDown">1</li>
    <li class="blue">2</li>
    <li class="blue">3</li>
    <li class="blue">4</li>
    <li>5</li>
    <li>6</li>
    <li>7</li>
</ul>

I'm trying to write jQuery to move item 1 down below the items with the class blue. To target the last item with that class, I'm using this:

$elm.nextUntil(":not(.blue)").last()

That seems like a mess, and it doesn't even work if there is only 1 blue item. There must be a better way to do this.

Here's the JSfiddle.

Current jQuery:

$("ul").on("click", ".moveMeDown", function(e){           
    var $elm = $(this);
        $elm
        .insertAfter($elm.nextUntil(":not(.blue)").last()) 
        .removeClass("blue");

});
Était-ce utile?

La solution

I'd suggest:

$('ul').on('click', '.moveMeDown', function(){
    var self = $(this);
    self.insertAfter(self.parent().find('.blue').last()).removeClass('blue');
});

JS Fiddle demo.

Also, as T.J. Crowder pointed out, in the comment below, the following also works:

$('ul').on('click', '.moveMeDown', function(){
    var self = $(this);
    self.insertAfter(self.siblings('.blue').last()).removeClass('blue');
});

JS Fiddle demo.

References:

Autres conseils

try this:

$("ul").on("click", ".moveMeDown", function(e){           
    var $elm = $(this);
    $(".blue:last").after($elm.removeClass("blue"));       
});

Or,

$("ul").on("click", ".moveMeDown", function(e){           
    var $lastBlue = $(this).parent().find(".blue").last(),
        $elm = $(this);

    $lastBlue.after($elm.removeClass("blue"));       
});

fiddle here: http://jsfiddle.net/Xb7ue/7/

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top