如何用动态ul id调用可排序函数?

时间:2017-01-02 13:24:05

标签: php jquery html ajax

我有多个ul并且我使ul id动态如:

<ul id='sortable1'><li></li><li></li></ul><ul id="sortable2"><li></li><li></li></ul><ul id="sortable3"><li></li><li></li></ul>

$( function() {
            $( "#sortable1" ).sortable({
                axis: 'y',
                update: function(event, ui) {
                    var unit_list_sortable = $(this).sortable('toArray').toString();
                    alert(unit_list_sortable);
                    $.ajax({
                        url: 'addPhaseUnits.php',
                        type: 'POST',
                        data: {unit_list_sortable:unit_list_sortable,action:'unit_sort_num'},
                        success: function(data) {
                        }
                    });
                }
            });
        });

如何使此功能可排序? UI正在循环工作,而id来自数据库。

2 个答案:

答案 0 :(得分:0)

此代码将使用插件数据表进行排序,搜索https://datatables.net/

下面的链接

$(document).ready(function(){
  $('#myTable').dataTable();
});
<!DOCTYPE html>
<html lang="en">
<head>
  <title>TABLE</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
   <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
	<script src="https://use.fontawesome.com/97755550d3.js"></script>
	<!--for search , sorting and tabl-->
	<link rel="stylesheet" href="http://cdn.datatables.net/1.10.2/css/jquery.dataTables.min.css">
	<script type="text/javascript" src="http://cdn.datatables.net/1.10.2/js/jquery.dataTables.min.js"></script>
</head>
<body>

<div class="col-md-12 table-responsive">
  <table class="table table-hover" id="myTable">
    <thead>
      <tr>
        <th>ID</th>
        <th>Uploaded Date</th>
      </tr>
    </thead>
    <tbody>
      <tr>
          <td>1</td>
          <td>01-01-2017</td>
       </tr>
      <tr>
          <td>2</td>
          <td>01-01-2017</td>
       </tr>
      <tr>
          <td>3</td>
          <td>01-01-2017</td>
       </tr>
      <tr>
          <td>4</td>
          <td>01-01-2017</td>
       </tr>
    </tbody>
  </table>
</div>
</body>
</html>

答案 1 :(得分:0)

您可以使用ID * jquery选择器

$( function() {
            $('[id*="sortable"]').sortable({
                axis: 'y',
                update: function(event, ui) {
                    var unit_list_sortable = $(this).sortable('toArray').toString();
                    alert(unit_list_sortable);
                    $.ajax({
                        url: 'addPhaseUnits.php',
                        type: 'POST',
                        data: {unit_list_sortable:unit_list_sortable,action:'unit_sort_num'},
                        success: function(data) {
                        }
                    });
                }
            });
        });