简体   繁体   中英

Optimal Method of Changing Order of Elements using jQuery

Given the following:

<a id="moveElementUp">Move Up</a>
<a id="moveElementDown">Move Dowm</a>

<div id="elementHolder">
    <a id="element-1">1</a>
    <a id="element-2">2</a>
    <a id="element-3">3</a>
    <a id="element-4">4</a>
</div>

<script type="text/javascript">
    function reOrder (el){
        // Change IDs of Elements to be Sequential
    }
    $('#moveElementUp').click(function(e){
        // Move Clicked Element Up One Spot in List

        reOrder();
    });
    $('#moveElementDown').click(function(e){
        // Move Clicked Element Down One Spot in List

        reOrder();
    });
</script>

What is the optimal (and fastest) way of going about changing the order of the elements and changing the IDs of all elements to maintain sequential order using jQuery?

Any help would be greatly appreciated!

This will let you rearrange items arbitrarily. However, it will remove the spaces between the anchor tags. You can solve this by adding spaces between the anchor tags (as I did here: http://jsfiddle.net/FqwDc/1/ ), or by using nested divs instead.

var $sel; // anchor last clicked on
var prefixstr = "element-";

$('a[id^="'+prefixstr+'"]').click(function(e) {
    $sel = $(this);
});
$('#moveElementUp').click(function(e) {
    // Move Clicked Element Up One Spot in List
    $sel.prev().before($sel);
    changeIDs($('#elementHolder'));
});
$('#moveElementDown').click(function(e) {
    // Move Clicked Element Down One Spot in List
    $sel.next().after($sel);
    changeIDs($('#elementHolder'));
});

function changeIDs($j) { // renumber the IDs
    $j.children('a').each(function(i) {
        $(this).attr('id',prefixstr+i);
    });
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM