Best way to iterate through a 'sortable' list and then change the values accordingly
I have a list of items in a list:
<ul id="myList">
<li>10 Apple</li>
<li>20 Banana</li>
<li>30 Orange</li>
</ul>
The list can be sorted thanks to jQuery. However once Ive arranged the items i need to recalculate their positions i.e Orange moved to top would equal 10, apple would then equal 20 and Banana 30.
I then need to pass this data in the url in order for my server side script to process.
What is the best way to be able to pass the altered list values into the URL when i submit?
开发者_Go百科My first thought was to have a form with hidden values, so when i process the list it adds the values into the form as hidden inputs in order for me to pass the data into the URL.
Is the number before each item strictly based on position?
If so, once the sort is complete you could just replace the content based on each li element.
Does it matter how the URL contains the list text?
In the below I operated with the assumption that it can all be appended with a querystring value of list.
There are shorter ways to do this, but hopefully the verbosity will aid in understanding what happens.
<script>
var listChanger = function() {
//updates the digits prepended to each item in list
//updates URL with text of list in querystring
//accumulates the text of each list item
var valueAccumulator = [];
//Operate of each item in myList
$('#myList li').each(function(index) {
//regular expression to strip initial digits
var reInitialDigits = /^\d+/;
//remove initial digits
var textWithoutDigits = $(this).text().replace(reInitialDigits,"");
//prepend new digits (index starts at 0, so add 1 then multiply by 10 to get desired number)
$(this).text(((index + 1) * 10) + textWithoutDigits);
//append text to accumulator
valueAccumulator.push($(this).text());
});
//querystring to strip everything after the querystring
var reQueryString = /\?list\=.*$/;
//placeholder
var linkWithoutQueryString = '';
//remove querystring
linkWithoutQueryString = $('#myLink').attr('href').replace(reQueryString,'');
//change link to include URL encoded list of values
$('#myLink').attr('href',linkWithoutQueryString + "?list=" + encodeURI(valueAccumulator.join("|")));
}
$(document).ready(function() {
//make the list sortable and each time the sorting stops, run the listChanger function
$("#myList").sortable({stop:listChanger});
});
</script>
<ul id="myList">
<li>10 Apple
</li>
<li>20 Banana
</li>
<li>30 Orange
</li>
</ul>
<br />
<a id="myLink" href="mylink.html">mylink.html</a>
精彩评论