当前位置: > > > jQuery - 第三方表格插件DataTables使用详解8(选中一行、选中多行)

jQuery - 第三方表格插件DataTables使用详解8(选中一行、选中多行)

十八、行选择功能

1,选择单行

(1)效果图
  • 如果点击的是未选中行,该行背景变成蓝色,表示被选中。如果之前已有其他选中的行,之前行则取消选中(蓝色背景消失)
  • 如果点击的是已选中行,则该行取消选中(蓝色背景消失)。
  • 点击最下方的删除按钮可以将当前选中行删除。

(2)样例代码
<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title></title>
    <script src="js/jquery-3.1.1.js"  type="text/javascript"></script>
    <script src="media/js/jquery.dataTables.js"  type="text/javascript"></script>
    <link rel="stylesheet" href="media/css/jquery.dataTables.css" type="text/css" />
    <script type="text/javascript">
      $(document).ready(function() {
        var table = $('#myTable').DataTable({
          "ajax": "data.txt"
        });

        //行点击事件响应
        $('#myTable tbody').on( 'click', 'tr', function () {
         if($(this).hasClass('selected')) {
             $(this).removeClass('selected');
         }
         else {
             table.$('tr.selected').removeClass('selected');
             $(this).addClass('selected');
         }
        });

        //删除选中行
        $('#button').click( function () {
            table.row('.selected').remove().draw(false);
        });
      });
    </script>
  </head>
  <body>
    <table id="myTable">
        <thead>
            <tr>
                <th>编号</th>
                <th>姓名</th>
                <th>出生日期</th>
            </tr>
        </thead>
    </table>
    <br>
    <button type="button" id="button">删除选中行</button>
  </body>
</html>


2,选择多行

(1)效果图
  • 如果点击未选中行时,该行背景变成蓝色,表示被选中。
  • 如果点击已选中行时,该行取消选中(蓝色背景消失)。
  • 点击最下方的统计按钮,会弹出显示当前选中行的数量。 

(2)样例代码
<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title></title>
    <script src="js/jquery-3.1.1.js"  type="text/javascript"></script>
    <script src="media/js/jquery.dataTables.js"  type="text/javascript"></script>
    <link rel="stylesheet" href="media/css/jquery.dataTables.css" type="text/css" />
    <script type="text/javascript">
      $(document).ready(function() {
        var table = $('#myTable').dataTable({
          "ajax": "data.txt"
        });

        //行点击事件响应
        $('#myTable tbody').on( 'click', 'tr', function () {
            $(this).toggleClass('selected');
        });

        //删除选中行
        $('#button').click( function () {
            alert('当前选中了' + table.rows('.selected').data().length + ' 行数据。');
        });
      });
    </script>
  </head>
  <body>
    <table id="myTable">
        <thead>
            <tr>
                <th>编号</th>
                <th>姓名</th>
                <th>出生日期</th>
            </tr>
        </thead>
    </table>
    <br>
    <button type="button" id="button">统计</button>
  </body>
</html>
评论0