Bootstrap-table使用记录

官方文档

Bootstrap-table 英文官方文档

练习的代码

HTML(Razor)代码:

<!-- index.cshtml -->

<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">&times;</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/*,
                cellStyle: function (row, index) {     // 单元格样式
                    css:{"background-color":"red"}  
                }*/
            },
            {
                title: '操作',
                formatter: operateFormatter,
                events: {
                    "click .mod": showUpdateModal,
                    "click .delete": deleteProduct
                }
            }
        ],
        onClickRow: function(row, $element, field) {    // events,详细见英文官方文档
            $('.success').removeClass('success');
            $($element).addClass('success');
        }/*,
        rowStyle: function (row, index) {    // 行样式
            var style = null;
            if (row.type == 1001) { // 简单样式
                style = 'success';
            }
            else {  // 复杂样式
                style = { css: { 'color': '#ed5565' } };
            }
            return { classes: style }
        }*/
    });

    /*需求:表格内过长内容折叠显示,可展开
      记录:可修改内容时,尽量不对元素进行动态拼接,避免绑定事件失效*/
    function tecParamFormatter(value, row, index) {
        if (value != null && value.length > 30) {
            return '<span class="tec-param">' + value.substr(0, textLength) + '...</span>&nbsp;<a class="toggle" href="javascript:void(0)">展开</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)">修改</a> '
            + '<a class="delete btn btn-danger" href="javascript:void(0)">删除</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;
        }

        // 使用了自定义confirm组件
        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("");
    });

    /*记录:表行点击事件监听JQuery版
    $table.on('click-row.bs.table', function (e, row, $element, field) {
        $('.success').removeClass('success');
        $($element).addClass('success');
        $aTable.bootstrapTable('refresh', { slient: true });
    });*/
});

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 () {
    // 基本和add差不多,略……
    });
};
/*common.js*/

/*提示*/
function tipsAlert(alertLevel, alertType, alertMessage) {
    $(".tipsAlert").removeClass("alert-success alert-warning alert-danger");
    $(".tipsAlert").addClass(alertLevel);
    $(".tipsAlert .alert-type").text(alertType);
    $(".tipsAlert .alert-message").text(alertMessage);
    $(".tipsAlert").fadeIn();

    $(".tipsAlert .close").click(function () {
        $(".tipsAlert").alert();
    });

    setTimeout(function () {
        $(".tipsAlert").fadeOut();
    }, 5000);
}

/*确认提示框*/
var Common = {
    confirm: function (params) {
        $("#confirmDialog").modal('show');
        var model = $("#confirmDialog");
        model.find(".message").html(params.message);

        model.find(".cancel").unbind("click");
        model.find(".ok").unbind("click");

        model.find(".ok").on("click", function () {
            params.operate(true);
        });

        model.find(".cancel").on("click", function () {
            params.operate(false);
        });
    }
};
/*common.css*/

/*提示框*/
.alert {
    display: none;
    position: fixed;
    bottom: 0px;
    right: 5px;
    z-index: 9;
}

/*修正表格内容过长溢出*/
.table {
    word-break:break-all;
    word-wrap:break-all;
}

posted on 2017-08-23 15:12  0Kelvin  阅读(326)  评论(0编辑  收藏  举报

导航