Dynamically arranging divs using jQuery

前端 未结 4 1325
再見小時候
再見小時候 2020-11-29 04:53

I have the following structure:

4条回答
  •  孤城傲影
    2020-11-29 05:27

    My plugin version - Working Demo

    Takes an array and optional id prefix and reorders elements whose ids correspond to the order of (id prefix) + values inside the array. Any values in the array that don't have an element with the corresponding id will be ignored, and any child elements that do not have an id within the array will be removed.

    (function($) {
    
    $.fn.reOrder = function(array, prefix) {
      return this.each(function() {
        prefix = prefix || "";
    
        if (array) {    
          for(var i=0; i < array.length; i++) 
            array[i] = $('#' + prefix + array[i]);
    
          $(this).empty();  
    
          for(var i=0; i < array.length; i++)
            $(this).append(array[i]);      
        }
      });    
    }
    })(jQuery);
    

    Code from the demo

    jQuery

     $(function() {
      $('#go').click(function() {
    
        var order = $('#order').val() == ""? null: $('#order').val().split(",");
        $('#container').reOrder(order, 'someid');
      });
    });
    
    (function($) {
    
    $.fn.reOrder = function(array, prefix) {
      return this.each(function() {
        prefix = prefix || "";
    
        if (array) {    
          for(var i=0; i < array.length; i++) 
            array[i] = $('#' + prefix + array[i]);
    
          $(this).empty();  
    
          for(var i=0; i < array.length; i++)
            $(this).append(array[i]);      
        }
      });    
    }
    })(jQuery);
    

    HTML

    
    
    
    
    reOrder Demo
    
    
    
    
    
    div1
    div2
    div3
    div4

    Pass in a comma separated list of numbers 1-4 to reorder divs

提交回复
热议问题