简体   繁体   English

用jQuery改变元素顺序的最优方法

[英]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? 使用jQuery改变元素顺序和更改所有元素的ID以维持顺序的最佳(和最快)方法是什么?

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. 你可以通过在锚标签之间添加空格来解决这个问题(就像我在这里做的那样: http//jsfiddle.net/FqwDc/1/ ),或者使用嵌套的div来代替。

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);
    });
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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