开发者

javascript looping through li attributes and changing values per item

I want to loop through a bunch of <li> elements and update the value held in it, and show this on t开发者_JAVA百科he document.

The reason i'm doing this is because I want to sort a list of elements in an order. I do this using Sortable in JQuery.

<li> 1 </li>
<li> 2 </li>
<li> 3 </li>
<li> 4 </li>
<li> 5 </li>

the order may become:

    <li> 3 </li>
    <li> 1 </li>
    <li> 4 </li>
    <li> 2 </li>
    <li> 5 </li>

Then clicking a button i would like my JS function to change the value of the li items back to 1,2,3,4,5. Its worth noting i am not looking for a solution to revert back to how the list was before.

Thanks.


This should work (as of jQuery 1.4):

$('.your_list li').text(function (index) {
    return index + 1;
});


I think you would rather reorder the list items than their contents. This way, you don't lose any of the li's attributes/classes/... And you can keep the DOM's elements intact, only change the order of some ul's children.

I found a nice little snippet do do it:

http://www.onemoretake.com/2009/02/25/sorting-elements-with-jquery/

The only thing you still need to do is remember the initial order

function mysortA( a, b ) {
   var compA = $(a).text().toUpperCase();
   var compB = $(b).text().toUpperCase();
   return (compA < compB) ? -1 : (compA > compB) ? 1 : 0;    
}
function mysortB( a, b ) {
  return   a.originalindex < b.originalindex ? -1 
         : a.originalindex > b.originalindex ?  1 
         : 0;
}

You have to initialize:

var ul = $('ul');
var listitems = ul.children('li').get();

// remember original index
listitems.each( function(index, li){ li.originalindex=index; } );

Then you can sort one way:

// sort them using your sort function
listitems.sort( mysort )
// rebuild the list container
listitems.each( function(idx, itm) { mylist.append(itm); });

And sort back:

var ul=$('ul');
ul.children('li').get().sort(mysortB).each(function(i,li){ ul.append(li); });

Note: untested - grab the idea.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜