Bootstrap table使用方法记录


Posted in Javascript onAugust 23, 2017

本文实例为大家分享了Bootstrap table的使用方法,供大家参考,具体内容如下

HTML代码:

/*index.cshtml*/

@section styles{
  <style>
    .main {
      margin-top:20px;
    }

    .modal-body .form-group .form-control {
      display:inline-block;
    }
    .modal-body .form-group .tips {
      color:red;
    }
  </style>
}

<div class="main">
  <div id="toolbar" class="btn-group">
    <button id="addProductBtn" type="button" class="btn btn-default" onclick="showAddModal()">
      <span class="glyphicon glyphicon-plus" aria-hidden="true"></span>新增产品
    </button>
  </div>

  <table id="table"></table>
</div>

<div class="modal fade" id="productModal" tabindex="-1" role="dialog" aria-labelledby="productModalLabel" aria-hidden="true">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
        <h4 class="modal-title" id="productModalLabel"></h4>
      </div>
      <div class="modal-body">
        <div class="form-group">
          <label for="prodId" class="col-md-2">编号:</label>
          <input type="text" class="form-control" id="prodId" disabled>
        </div>
        <div class="form-group">
          <label for="prodName" class="col-md-2">名称:</label>
          <input type="text" class="form-control" id="prodName">
          <span class="tips" >(最多20个字)</span>
        </div>
        <div class="form-group">
          <label for="prodTecParam" class="col-md-2">技术参数:</label>
          <textarea rows="3" class="form-control" id="prodTecParam"></textarea>
          <span class="tips" >(最多150个字)</span>
        </div>
        <div class="form-group">
          <label for="prodType" class="col-md-2">类型:</label>
          <select class="form-control" id="prodType">
            <option value="1001">普通产品</option>
            <option value="1002">明星产品</option>
          </select>
        </div>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
        <button id="modalSubmitBtn" type="button" class="btn btn-primary">{{modalBtn}}</button>
      </div>
    </div><!-- /.modal-content -->
  </div><!-- /.modal -->
</div>

@section scripts{
  <script type="text/javascript" src="~/Scripts/bootstrap-table.js"></script>
  <script type="text/javascript" src="~/Scripts/bootstrap-table-zh-CN.js"></script>
  <script type="text/javascript" src="~/Scripts/common.js"></script>
  <script type="text/javascript" src="~/Views/Home/index.js"></script>
}

JS代码:

/*index.js*/

$(document).ready(function () {
  var $table = $('#table');
  var textLength = 30;  //技术参数默认折叠显示长度

  $table.bootstrapTable({
    locale: 'zh-CN',
    url: '/product/getList',
    method: 'post',
    contentType: 'application/json',
    dataType: "json",
    toolbar: '#toolbar',        //工具按钮用哪个容器
    pagination: true,
    search: true,
    showRefresh: true,
    sidePagination: "server",      //分页方式:client客户端分页,server服务端分页
    singleSelect: true,         //单行选择
    pageNumber: 1,           //初始化加载第一页,默认第一页
    pageSize: 10,            //每页的记录行数
    pageList: [5, 10, 20],
    queryParams: function (params) {  //请求参数
      var temp = {
        pageSize: params.limit,           //页面大小
        pageNo: params.offset / params.limit + 1,  //页码
        search: $('.search input').val()
      };

      return temp;
    },
    responseHandler: function (res) {
      return {
        pageSize: res.pageSize,
        pageNumber: res.pageNo,
        total: res.total,
        rows: res.rows
      };
    },
    columns: [
      {
        title: '产品编号',
        field: 'id'
      },
      {
        title: '产品名称',
        width: 200,
        field: 'name'
      },
      {
        title: '技术参数',
        field: 'tecParam',
        width: 300,
        formatter: tecParamFormatter,
        events: {
          "click .toggle": toggleText
        }
      },
      {
        title: '类型',
        field: 'type',
        formatter: typeFormatter
      },
      {
        title: '操作',
        formatter: operateFormatter,
        events: {
          "click .mod": showUpdateModal,
          "click .delete": deleteProduct
        }
      }
    ]
  });

  function tecParamFormatter(value, row, index) {
    if (value != null && value.length > 30) {
      return '<span class="tec-param">' + value.substr(0, textLength) + '...</span> <a class="toggle" href="javascript:void(0)" rel="external nofollow" rel="external nofollow" rel="external nofollow" >展开</a>';
    }
    return value;
  }
  
  function toggleText(e, value, row, index) {
    if (value == null) {
      return false;
    }

    var $tecParam = $(this).prev(".tec-param"),
      $toggle = $(this);

    if ($tecParam.text().length > textLength + 5) { //折叠
      $tecParam.text(value.substr(0, textLength) + "...");
      $toggle.text("展开");
    }
    else if (value.length > textLength + 5 && $tecParam.text().length <= textLength + 5) {  //展开
      $tecParam.text(value);
      $toggle.text("折叠");
    }
  }

  function typeFormatter(value, row, index) {
    var type = "";
    if (value == "1001")
      type = "普通产品";
    else if (value == "1002")
      type = "明星产品";
    return type;
  };

  function operateFormatter (value, row, index) {
    return '<a class="mod btn btn-info" href="javascript:void(0)" rel="external nofollow" rel="external nofollow" rel="external nofollow" >修改</a> '
      + '<a class="delete btn btn-danger" href="javascript:void(0)" rel="external nofollow" rel="external nofollow" rel="external nofollow" >删除</a>';
  };

  function showUpdateModal (e, value, row, index) {
    $("#productModalLabel").text("更新产品信息");
    $("#modalSubmitBtn").text("更新");

    $("#prodId").val(row.id);
    $("#prodId").attr("disabled", true);  //禁止修改id
    $("#prodName").val(row.name);
    $("#prodTecParam").val(row.tecParam);
    if (row.type == 1001)
      $("#prodType").find('option[value="1001"]').attr("selected", true);
    else if (row.type == 1002)
      $("#prodType").find('option[value="1002"]').attr("selected", true);

    $("#modalSubmitBtn").unbind();
    $("#modalSubmitBtn").on("click", updateProduct);

    $("#productModal").modal("show");
  };


  function deleteProduct (e, value, row, index) {
    var product = {
      id: row.id
    };
    if (product.id === null || product.id === "") {
      return false;
    }

    Common.confirm({
      message: "确认删除该产品?",
      operate: function (result) {
        if (result) {
          $.ajax({
            type: "post",
            url: "/product/delete",
            contentType: "application/json",
            data: JSON.stringify(product),
            success: function (data) {
              if (data !== null) {
                if (data.result) {
                  $("#table").bootstrapTable("refresh", { silent: true });
                  tipsAlert('alert-success', '提示', '删除成功!');
                }
                else {
                  tipsAlert('alert-warning', '提示', '删除失败!');
                }
              }
            },
            error: function (err) {
              tipsAlert('alert-danger', '警告', '服务器异常,请稍后再试!');
              console.log("error:", err.statusText);
            }
          });

          return true;
        }
        else {
          return false;
        }
      }
    });
  };

  var $search = $table.data('bootstrap.table').$toolbar.find('.search input');
  $search.attr('placeholder', '请输入编号、产品名称、技术参数搜索');
  $search.css('width', '400');

  $(".model .form-group input").on("click", function(){
    $(this).next(".tips").text("");
  });
});

var showAddModal = function () {
  $("#productModalLabel").text("新增产品");
  $("#modalSubmitBtn").text("新增");

  $("#prodId").val('');
  $("#prodName").val('');
  $("#prodTecParam").val('');

  $("#modalSubmitBtn").unbind();
  $("#modalSubmitBtn").on("click", addProduct);

  $("#productModal").modal("show");
};

var addProduct = function () {
  var product = {
    name: $("#prodName").val(),
    tecParam: $("#prodTecParam").val(),
    type: $("#prodType").val()
  };
  if (product.name == null || product.name == "") {
    $("#prodName").next(".tips").text("产品名称不能为空!");
    return false;
  }
  if (product.name.length > 20) {
    $("#prodName").next(".tips").text("最多20个字!");
    return false;
  }
  if (product.tecParam.length > 150) {
    $("#prodTecParam").next(".tips").text("最多150个字!");
    return false;
  }

  $.ajax({
    type: "post",
    url: "/product/add",
    contentType: "application/json",
    data: JSON.stringify(product),
    success: function (data) {
      if (data !== null) {
        if (data.result) {
          $("#table").bootstrapTable("refresh", { silent: true });
          $("#productModal").modal('hide');
          $("#prodId").val('');
          $("#prodName").val('');
          $("#prodTecParam").val('');
          tipsAlert('alert-success', '提示', '新增成功!');
        }
        else {
          tipsAlert('alert-warning', '提示', '新增失败!');
        }
      }
    },
    error: function (err) {
      tipsAlert('alert-danger', '警告', '服务器异常,请稍后再试!');
      console.log("error:", err.statusText);
    }
  });
};

var updateProduct = function () {
  var product = {
    id: $("#prodId").val(),
    name: $("#prodName").val(),
    tecParam: $("#prodTecParam").val(),
    type: $("#prodType").val()
  };
  if (product.name == null || product.name == "") {
    $("#prodName").next(".tips").text("产品名称不能为空!");
    return false;
  }
  if (product.name.length > 20) {
    $("#prodName").next(".tips").text("最多20个字!");
    return false;
  }
  if (product.tecParam.length > 150) {
    $("#prodTecParam").next(".tips").text("最多150个字!");
    return false;
  }

  $.ajax({
    type: "post",
    url: "/product/update",
    contentType: "application/json",
    data: JSON.stringify(product),
    success: function (data) {
      if (data !== null) {
        if (data.result) {
          $("#table").bootstrapTable("refresh", { silent: true });
          $("#productModal").modal('hide');
          $("#prodId").val('');
          $("#prodName").val('');
          $("#prodTecParam").val('');
          tipsAlert('alert-success', '提示', '修改成功!');
        }
        else {
          tipsAlert('alert-warning', '提示', '修改失败!');
        }
      }
    },
    error: function (err) {
      tipsAlert('alert-danger', '警告', '服务器异常,请稍后再试!');
      console.log("error:", err.statusText);
    }
  });
};

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持三水点靠木。

Javascript 相关文章推荐
5分钟理解JavaScript中this用法分享
Nov 09 Javascript
js控制input输入字符解析
Dec 27 Javascript
window.location的重写及判断location是否被重写
Sep 04 Javascript
javascript制作sql转换为stringBuffer的小工具
Apr 03 Javascript
遍历json 对象的属性并且动态添加属性的实现
Dec 02 Javascript
ES6正则表达式扩展笔记
Jul 25 Javascript
小程序登录态管理的方法示例
Nov 13 Javascript
vue拖拽排序插件vuedraggable使用方法详解
Aug 21 Javascript
谈谈React中的Render Props模式
Dec 06 Javascript
node.js express捕获全局异常的三种方法实例分析
Dec 27 Javascript
浅谈JavaScript中你可能不知道URL构造函数的属性
Jul 13 Javascript
js实现滑动进度条效果
Aug 21 Javascript
JS实现浏览上传文件的代码
Aug 23 #Javascript
基于jQuery实现的单行公告活动轮播效果
Aug 23 #jQuery
JS轮播图实现简单代码
Feb 19 #Javascript
详解AngularJS1.x学习directive 中‘&amp; ’‘=’ ‘@’符号的区别使用
Aug 23 #Javascript
JavaScript实现的数字与字符串转换功能示例
Aug 23 #Javascript
最基础的vue.js双向绑定操作
Aug 23 #Javascript
vue组件实现文字居中对齐的方法
Aug 23 #Javascript
You might like
全国FM电台频率大全 - 11 浙江省
2020/03/11 无线电
Linux fgetcsv取得的数组元素为空字符串的解决方法
2011/11/25 PHP
使用YII2框架实现微信公众号中表单提交功能
2017/09/04 PHP
PHP工厂模式、单例模式与注册树模式实例详解
2019/06/03 PHP
解决thinkphp5未定义变量会抛出异常,页面错误,请稍后再试的问题
2019/10/16 PHP
10款新鲜出炉的 jQuery 插件(Ajax 插件,有幻灯片、图片画廊、菜单等)
2011/06/08 Javascript
javascript中var的重要性分析
2015/02/11 Javascript
javascript作用域问题实例分析
2015/07/13 Javascript
Web程序员必备的7个JavaScript函数
2016/06/14 Javascript
zTree实现节点修改的实时刷新功能
2017/03/20 Javascript
基于javascript的异步编程实例详解
2017/04/10 Javascript
JavaScript原型对象原理与应用分析
2018/12/27 Javascript
vue props对象validator自定义函数实例
2019/11/13 Javascript
js实现有趣的倒计时效果
2021/01/19 Javascript
[01:02:25]2014 DOTA2华西杯精英邀请赛5 24 NewBee VS VG
2014/05/25 DOTA
[04:01]2014DOTA2国际邀请赛 TITAN告别Ohaiyo期望明年再战
2014/07/15 DOTA
python实现同时给多个变量赋值的方法
2015/04/30 Python
Django的数据模型访问多对多键值的方法
2015/07/21 Python
基于pandas数据样本行列选取的方法
2018/04/20 Python
python通过配置文件共享全局变量的实例
2019/01/11 Python
Python增强赋值和共享引用注意事项小结
2019/05/28 Python
python3反转字符串的3种方法(小结)
2019/11/07 Python
快速解决pymongo操作mongodb的时区问题
2020/12/05 Python
python 录制系统声音的示例
2020/12/21 Python
Python 将代码转换为可执行文件脱离python环境运行(步骤详解)
2021/01/25 Python
世界上最受欢迎的钓鱼诱饵:Rapala
2019/05/02 全球购物
大学生找工作推荐信范文
2013/11/28 职场文书
企业车辆管理制度
2014/01/24 职场文书
数学教学随笔感言
2014/02/17 职场文书
听课评语大全
2014/04/30 职场文书
行政管理专业求职信
2014/07/06 职场文书
法英专业大学生职业生涯规划书范文
2014/09/22 职场文书
乡镇党的群众路线教育实践活动个人整改方案
2014/10/31 职场文书
三潭印月的导游词
2015/02/12 职场文书
2015年中学图书馆工作总结
2015/07/22 职场文书
详解PyTorch模型保存与加载
2022/04/28 Python