开发者

Move an attribute to the previous item in a list

How can I move the href attribute of a series of links on a list up (backwards) with jQuery?

This is my list:

<ul id="mylist">
  <li><a href="#one">1</a></li>
  <li><a href="#two">2</a></li>
  <li><a href="#three">3</a></li>
</ul>

Would need to be:

<ul id="mylis开发者_如何转开发t">
  <li><a href="#two">1</a></li>
  <li><a href="#three">2</a></li>
  <li><a href="#one">3</a></li>
</ul>

Would it would be best to do this in some kind of $.each() loop? The text inside and the href values are dynamic.

$('#mylist a').each(function(i) { ??? });

Not sure how to go about actually storing the current href and moving it to the previous one while doing the same to the previous one... and then moving the first one to the end.


jQuery.fn.reverse = [].reverse;

var $li = $('#mylist li a');
var prevhref = $li.first().attr('href');
$li.reverse().each(function() {
    var $this = $(this);
    var nexthref = $this.attr('href');
    $this.attr('href', prevhref);
    prevhref = nexthref;
});

Similar, a mite faster:

jQuery.fn.reverse = [].reverse;

var $li = $('#mylist li a');
var prevhref = $li[0].getAttribute('href');
$li.reverse().each(function() {
    var nexthref = this.getAttribute('href');
    this.setAttribute('href', prevhref);
    prevhref = nexthref;
});


Quick and untested:

    var elements = $('#mylist a');

    for (var i = 0; i < elements.length - 1; i++) {
      var t = $(elements[i + 1]).attr('href');
      $(elements[i + 1]).attr('href') = $(elements[i]).attr('href');
      $(elements[i]).attr('href') = t;
    }


Can't think how you'd do it with the built in methods, but looping works OK

var items = $('#mylist a'), lastItem, thisItem;
//hold onto the first href for a bit, we'll apply it to the last one once we're done
var firstHref = items.first().attr('href')
//spin through the rest
for (var i = 0; i< items.length; i++) {
    thisItem = items.eq(i);
    if (lastItem) {
        lastItem.attr('href', thisItem.attr('href'));
    }
    lastItem = thisItem;
}
items.last().attr('href', firstHref);

Try it live

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜