4

我试图通过用数字定义类来将具有类名的 div 容器插入到带有其他容器的框​​中。

只要标记已经按时间顺序排列,我就能使以下内容正常工作:

http://play.meyouand.us/140418-rearrange/rearrange4a.html

但是,如果标记顺序是混合的或相反的时间顺序,则该函数不会将 div 容器定位在确切的位置(因为我使用的函数是 before()):

http://play.meyouand.us/140418-rearrange/rearrange4b.html

我目前坚持如何解决这个问题,因为我不确定我是否应该首先使用预先对盒子进行排序的策略,或者是否有一个现有的 jQuery 函数可以将 div 容器准确地放置在我需要它们的位置将使其成为理想而简单的解决方案。任何关于策略或方法的想法都会有所帮助!

jQuery 到目前为止... - http://jsfiddle.net/foomarks/qM27z/2/

$('[class*=order-]').each(function() {

        /* 1. Split the classes to get an array */      
        var cl = $(this).prop('class').split(/\s+/);
        var clNumber = cl.map( function(val){
            if (val.indexOf('order-') !== -1) {  //find the match
            return val.replace( /^\D+/g, '')  // return back the number
            }
        });
        console.log("clNumber: " + clNumber[1]);

        /* 2. Presort boxes */
            /* Strategy A 
               . If this clNumber is greater than the next .order- box, append it after 
               . else do nothing 
            */

            /* Strategy B
               . Sort the array
               . then .append() the output
               . this may not work within the .each function because of sequencing
            */

        /* 3. Use the insert number to reposition */
        $(this).insertBefore('.box:nth-child('+ clNumber[1] + ')');    
    });
4

2 回答 2

4

我的解决方案是这样的:

  1. 停止使用类来存储变量;这就是data-属性的用途。
  2. 遍历要移动的元素,创建一个 {element,order} 对数组
  3. 将对排序为正确的顺序
  4. 循环执行插入的对。

工作演示:http: //jsfiddle.net/qM27z/3/

var tomove =
    $('[data-order]').map(function() {
        return { element: this, order: $(this).data("order") };
    }).get().sort(function(a,b) { return a.order-b.order; });

$.each(tomove, function(i, tm) {
    $(tm.element).insertBefore('.container .box:nth-child('+tm.order+')')
});
于 2014-04-24T20:22:40.480 回答
1

我觉得有一种更清洁的方法可以做到这一点,但这很有效:

jsFiddle 示例

var ary1 = $('div[class*="order-"]');
var ary2 = $('div.container div.box');
var total = ary1.length + ary2.length;
$('.container').empty();
for (var i = 1; i <= total; i++) {
    var match = false;
    ary1.each(function () {
        var cl = $(this).prop('class').split(/\s+/);
        var clNumber = cl.map(function (val) {
            if (val.indexOf('order-') !== -1) { //find the match
                return val.replace(/^\D+/g, '') // return back the number
            }
        });
        if (clNumber[1] == i) {
            $(this).appendTo('.container');
            match = true;
        }
    })
    if (!match) $('<div class="box">Box</div>').appendTo('.container')
}
于 2014-04-22T20:10:32.763 回答