【问题标题】:Reorder table columns using Drag and Drop with jQuery使用 jQuery 拖放重新排序表列
【发布时间】:2016-10-22 14:57:30
【问题描述】:

我想允许用户通过拖放来重新排列表格中的列。我正在使用 jquery.dragtable.js 来允许拖放。它工作正常。现在我想在客户端存储拖放后的表格顺序并恢复onload状态。

这是我的 HTML 代码:

<table id="tblReg" class="table table-bordered">
    <thead>
        <tr>
            <th>#</th>
            <th>First Name</th>
            <th>Last Name</th>
            <th>Username</th>
            <th>Password</th>
            <th>Email</th>
            <th>Phone</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <th>1</th>
            <td>Mark</td>
            <td>Otto</td>
            <td>@mdo</td>
            <td>545trt574</td>
            <td>Na@email.com</td>
            <td>7788994320</td>
        </tr>
        <tr>
            <th>2</th>
            <td>Jacob</td>
            <td>Thornton</td>
            <td>@fat</td>
            <td>yffft5456</td>
            <td>Na@email.com</td>
            <td>7788994320</td>
        </tr>
        <tr>
            <th>3</th>
            <td>Larry</td>
            <td>the Bird</td>
            <td>@twitter</td>
            <td>fgfhgf444</td>
            <td>Na@email.com</td>
            <td>7788994320</td>
        </tr>
        <tr>
            <th>4</th>
            <td>Rima</td>
            <td>the Bird</td>
            <td>@twitter</td>
            <td>jjk8899</td>
            <td>Na@email.com</td>
            <td>7788994320</td>
        </tr>
        <tr>
            <th>5</th>
            <td>Sundar</td>
            <td>the Bird</td>
            <td>@twitter</td>
            <td>76767687hjh</td>
            <td>Na@email.com</td>
            <td>7788994320</td>
        </tr>
    </tbody>
</table>

<a href="#" class="order">Get Table Order</a>
<p class="porder"></p>

jquery:

$(document).ready(function(){
    $('#tblReg').each(function(){
        $(this).dragtable({
            placeholder: 'dragtable-col-placeholder',
            items: 'thead th:not( .notdraggable ):not( :has( .dragtable-drag-handle ) ), .dragtable-drag-handle',
            appendTarget: $(this).parent(),
            scroll: true
        });
    });
    $('a.order').click(function(){
        console.log($('#tblReg').dragtable('order'));
        var curOrder = $('#tblReg').dragtable('order');
        $('.porder').text(curOrder);
        return false;
    });
}); 

插件参考:https://github.com/akottr/dragtable

允许提供获取表格顺序如下:

["#", "First Name", "Last Name", "Username", "Password", "Email", "Phone"]

现在我想将它存储在客户端(LocalStorage / Cookies)并根据保存数据重新排序 OnLoad。

如何做到这一点?我是 jquery 的新手。

【问题讨论】:

    标签: javascript jquery html drag-and-drop


    【解决方案1】:

    试试这个代码,它工作正常。

    在拖放后将列排序设置到 sessionStorage 中,然后刷新您的页面。您将看到列顺序发生变化。

    以数组格式排序记录,您可以在控制台中看到:

    <!DOCTYPE html>
    <html>
    <head>
    	<title>Reorder</title>
    	<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
      <link rel="stylesheet" type="text/css" href="//rawgithub.com/akottr/dragtable/master/dragtable.css" />
    </head>
    <body>
    <div class="container-fluid">
      <div class="row">
        <div class="col-sm-12">
          <table id="tblReg" class="table table-bordered">
            <thead>
              <tr class="active">
                <th id="number">#</th>
                <th id="fname">First Name</th>
                <th id="lname">Last Name</th>
                <th id="uname">Username</th>
                <th id="pass">Password</th>
                <th id="email">Email</th>
                <th id="phone">Phone</th>
              </tr>
            </thead>
            <tbody>
              <tr>
                <th>1</th>
                <td>Mark</td>
                <td>Otto</td>
                <td>@mdo</td>
                <td>545trt574</td>
                <td>Na@email.com</td>
                <td>7788994320</td>
              </tr>
              <tr>
                <th>2</th>
                <td>Jacob</td>
                <td>Thornton</td>
                <td>@fat</td>
                <td>yffft5456</td>
                <td>Na@email.com</td>
                <td>7788994320</td>
              </tr>
              <tr>
                <th>3</th>
                <td>Larry</td>
                <td>the Bird</td>
                <td>@twitter</td>
                <td>fgfhgf444</td>
                <td>Na@email.com</td>
                <td>7788994320</td>
              </tr>
              <tr>
                <th>4</th>
                <td>Rima</td>
                <td>the Bird</td>
                <td>@twitter</td>
                <td>jjk8899</td>
                <td>Na@email.com</td>
                <td>7788994320</td>
              </tr>
              <tr>
                <th>5</th>
                <td>Sundar</td>
                <td>the Bird</td>
                <td>@twitter</td>
                <td>76767687hjh</td>
                <td>Na@email.com</td>
                <td>7788994320</td>
              </tr>
            </tbody>
          </table>
        </div>
      </div>
    
      <div class="row">
        <div class="col-sm-12">
          <a href="#" class="btn btn-info order">Get Table Order</a>
          <p class="porder"></p>
        </div>
      </div>
    </div>
    
    
    
    
    <script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
    <script src="//ajax.googleapis.com/ajax/libs/jqueryui/1.10.2/jquery-ui.min.js"></script>
    <script src="//rawgithub.com/akottr/dragtable/master/jquery.dragtable.js"></script>
    
    
    <script type="text/javascript">
    $(document).ready(function(){
      // this code for sessionStorage
      $('#tblReg').dragtable({ 
        persistState: function(table) { 
          if (!window.sessionStorage) return; 
          var ss = window.sessionStorage; 
          table.el.find('th').each(function(i) { 
            if(this.id != '') {table.sortOrder[this.id]=i;} 
          }); 
          ss.setItem('tableorder', JSON.stringify(table.sortOrder)); 
        }, 
        restoreState: eval('(' + window.sessionStorage.getItem('tableorder') + ')') 
      });
    
      // this code for each th drag and drop 
      $('#tblReg').each(function(){
        $(this).dragtable({
          placeholder: 'dragtable-col-placeholder',
          items: 'thead th:not(.notdraggable):not(:has(.dragtable-drag-handle)), .dragtable-drag-handle',
          appendTarget: $(this).parent(),
          scroll: true
        });
      });
    
      // Click and then you see ordering of (th) in console.
      $('a.order').click(function(e){
        e.preventDefault();
        var order_array = [];
        $('#tblReg').dragtable().find('thead th').each(function(i,v){
          order_array.push($(v).text());
        });
        console.log(order_array);
        $('.porder').text(order_array);
      }); 
    
    }); 
    </script>
    </body>
    </html>

    【讨论】:

    • 但在页面刷新表顺序后不会根据控制台数组更改
    • 我想使用 localStorage 而不是 sessionStorage @Raeesh
    • 点击“获取表格顺序”按钮后,控制台数组将发生变化。我正在尝试使用 localStorage @sandy 来解决
    【解决方案2】:

    尝试使用此代码在 localStorage 中存储列订单。

      //For localstorage
      $('#tblReg').dragtable({ 
        persistState: function(table) { 
          if (!window.localStorage) return; 
          var ss = window.localStorage; 
          table.el.find('th').each(function(i) { 
            if(this.id != '') {table.sortOrder[this.id]=i;} 
          }); 
          ss.setItem('tableorder', JSON.stringify(table.sortOrder));
         $('a.order').trigger('click');//When drop the column then button will trigger 
        }, 
        restoreState: eval('(' + window.localStorage.getItem('tableorder') + ')') 
      });
    

    【讨论】:

    • 这里你也使用 ID 和 的活动类但是它不需要添加 ID 因为我的表是动态生成的。
    • 它与 id 一起工作正常。但是我的表是动态生成的,为什么我需要没有 td id @Raeesh
    • 谢谢@sandy。因为在 localStorage 中需要唯一的身份来设置和获取记录。听起来很适合您的需求,我正在尝试在没有 id 的情况下解决这个问题,然后将在此处发布...
    • 嗨 Raeesh 我已经为动态 ID 生成创建了一个代码,并且工作正常。但是当我添加一个或多个表时它不起作用。
    • 嗨@JargoViet。好的,如果您希望多个表在 localStorage 中存储订单,那么您将需要不同的 table idth id 以及不同的 setItem name 并且在初始化之后ids 到 JavaScript 代码中。谢谢
    【解决方案3】:

    我做到了!请检查是否有错误。

    $(document).ready(function(){
        //localStorage.clear();
        var tblReg  = $('#tblReg').attr('id');
        var tblRegMaster = $('#tblRegMaster').attr('id');
    
        processDnD(tblReg);
        processDnD(tblRegMaster);
    
    });
    
    
    function processDnD(cuTable){
        var tblName = cuTable;
        $('#'+cuTable).find('th').each(function() {
            var ctxt = $(this).text();
            if(ctxt == 'First Name'){
                $(this).attr('id','firstName-'+tblName);
            }else if(ctxt == 'Password'){
                $(this).attr('id','password'+tblName);
            }else if(ctxt == 'Email'){
                $(this).attr('id','iemail'+tblName);
            }else if(ctxt == 'Username'){
                $(this).attr('id','userName'+tblName);
            }else if(ctxt == 'Last Name'){
                $(this).attr('id','lastName'+tblName);
            }else if(ctxt == '#'){
                $(this).attr('id','slNo'+tblName);
            }else if(ctxt == 'Phone'){
                $(this).attr('id','phone'+tblName);
            }else if(ctxt == 'PO Number'){
                $(this).attr('id','pono'+tblName);
            }else if(ctxt == 'Shipper'){
                $(this).attr('id','shipperName'+tblName);
            }else if(ctxt == 'Status'){
                $(this).attr('id','cuStatus'+tblName);
            }else if(ctxt == 'Booking Line'){
                $(this).attr('id','BookingLine'+tblName);
            }else if(ctxt == 'Access Mode'){
                $(this).attr('id','AccessMode'+tblName);
            }else if(ctxt == 'Container No'){
                $(this).attr('id','ContainerNo'+tblName);
            }
        })
    
        $('#'+cuTable).dragtable({ 
            persistState: function(table) { 
            if (!window.localStorage) return; 
                var ss = window.localStorage; 
                table.el.find('th').each(function(i) { 
                if(this.id != '') {table.sortOrder[this.id]=i;} 
            }); 
            ss.setItem('setTableOrder-'+tblName, JSON.stringify(table.sortOrder)); 
            }, 
            restoreState: eval('(' + window.localStorage.getItem('setTableOrder-'+tblName) + ')') 
        });
    
        $('#'+cuTable).each(function(){
            $(this).dragtable({
                placeholder: 'dragtable-col-placeholder',
                items: 'thead th:not(.notdraggable):not(:has(.dragtable-drag-handle)), .dragtable-drag-handle',
                appendTarget: $(this).parent(),
                scroll: true
            })
        }); 
    }
    

    【讨论】:

      猜你喜欢
      相关资源
      最近更新 更多
      热门标签