search
HomeWeb Front-endJS TutorialSummary of the use of bootstrap-table in BootStrap

本篇文章就给大家介绍带来BootStrap之bootstrap-table使用总结 。有一定的参考价值,有需要的朋友可以参考一下,希望对你们有所帮助。如果大家想要学习和获取更多的bootstrap相关视频教程也可以访问:bootstrap教程

一、下载:

https://github.com/wenzhixin/bootstrap-table

二、文档:

http://bootstrap-table.wenzhixin.net.cn/zh-cn/documentation/

三、引用:

<link>
<link>

<script></script>
<script></script>
<script></script>
<script></script>

注意:最后一个是一些提醒文字,如果有引用这个js则会以中文提示,如果没有则以英文提示。

四、基本用法:

html里:


js里:

        $('#table').bootstrapTable({
            columns: [{
                field: 'id',
                title: 'Item ID'
            }, {
                field: 'name',
                title: 'Item Name'
            }, {
                field: 'price',
                title: 'Item Price'
            }],
            data: [{
                id: 1,
                name: 'Item 1',
                price: '$1'
            }, {
                id: 2,
                name: 'Item 2',
                price: '$2'
            }]
        });

这个data也可以换成url:

$('#table').bootstrapTable({
    url: 'data1.json',
    columns: [{
        field: 'id',
        title: 'Item ID'
    }, {
        field: 'name',
        title: 'Item Name'
    }, {
        field: 'price',
        title: 'Item Price'
    }, ]
});

注意:url和data的区别是:url是异步请求远程数据;data是直接把数据赋值给他。在主表和子表都一样可以这样使用。

五、引入fonts:

一些图标需要用到bootstrap里面的文件,要从下载的bootstrap包里面拷贝过来放到对应的目录(看错误提醒)。

但是只放进去是访问不了的,因为他不是普通的文件,所以要设置。

进入iis管理器,找到“MIME类型”,双击进去,在右边菜单点击“添加”,分别添加以下类型:

.woff
application/x-font-woff

.woff2          
application/x-font-woff

再刷新页面就可以加载fonts里面这些文件了。

六、定制组件

(function () {
    function init(table,url,params,titles,hasCheckbox,toolbar) {
        $(table).bootstrapTable({
            url: url,                           //请求后台的URL(*)
            method: 'post',                     //请求方式(*)
            toolbar: toolbar,                   //工具按钮用哪个容器
            striped: true,                      //是否显示行间隔色
            cache: false,                       //是否使用缓存,默认为true,所以一般情况下需要设置一下这个属性(*)
            pagination: true,                   //是否显示分页(*)
            sortable: false,                    //是否启用排序
            sortOrder: "asc",                   //排序方式
            queryParams: queryParams,           //传递参数(*),这里应该返回一个object,即形如{param1:val1,param2:val2}
            sidePagination: "server",           //分页方式:client客户端分页,server服务端分页(*)
            pageNumber:1,                       //初始化加载第一页,默认第一页
            pageSize: 20,                       //每页的记录行数(*)
            pageList: [20, 50, 100],            //可供选择的每页的行数(*)
            search: true,                       //是否显示表格搜索,此搜索是客户端搜索,不会进服务端,所以,个人感觉意义不大
            strictSearch: true,
            showColumns: true,                  //是否显示所有的列
            showRefresh: true,                  //是否显示刷新按钮
            minimumCountColumns: 2,             //最少允许的列数
            clickToSelect: true,                //是否启用点击选中行
            //height: 500,                      //行高,如果没有设置height属性,表格自动根据记录条数觉得表格高度
            uniqueId: "ID",                     //每一行的唯一标识,一般为主键列
            showToggle:true,                    //是否显示详细视图和列表视图的切换按钮
            cardView: false,                    //是否显示详细视图
            detailView: false,                  //是否显示父子表

            columns: createCols(params,titles,hasCheckbox),
            data: [{
                id: 1,
                name: 'Item 1',
                price: '$1'
            }, {
                id: 2,
                name: 'Item 2',
                price: '$2'
            }]
        });
    }
    function createCols(params,titles,hasCheckbox) {
        if(params.length!=titles.length)
            return null;
        var arr = [];
        if(hasCheckbox)
        {
            var objc = {};
            objc.checkbox = true;
            arr.push(objc);
        }
        for(var i = 0;i<params.length>pageSize,offset->pageNumber,search->searchText,sort->sortName(字段),order->sortOrder('asc'或'desc')
    function queryParams(params) {
        return {   //这里的键的名字和控制器的变量名必须一直,这边改动,控制器也需要改成一样的
            limit: params.limit,   //页面大小
            offset: params.offset  //页码
            //name: $("#txt_name").val()//关键字查询
        };
    }
    // 传'#table'
    createBootstrapTable = function (table,url,params,titles,hasCheckbox,toolbar) {
        init(table,url,params,titles,hasCheckbox,toolbar);
    }

})();</params.length>
1、调用:
createBootstrapTable('#table','',['id','name','price'],['Item ID','Item Name!','Item Price!'],true,'#toolbar');
2、模块:

注意,这些只要添加上一行代码就会自动显示的:

pagination 显示分页
search     搜索功能
showColumns  控制显示哪些列的按钮
showRefresh  刷新按钮
showToggle   详细视图和列表视图切换按钮

但是这个不会:

toolbar

这个toolbar会关联到我们填的一个元素,但是他并不会自动创建所有菜单,而是我们要创建好菜单,他只不过把这个菜单放到合适的位置,实现这些菜单的功能还需要我们自己去做。toolbar如下:

    <p>
        <button>
            <span></span>新增
        </button>
        <button>
            <span></span>修改
        </button>
        <button>
            <span></span>删除
        </button>
    </p>
3、sidePagination

这个是选择服务端或者客户端分页,客户端则填'client',服务端则填'server',他们的数据结构是不同的。

这是客户端分页的数据结构:

[
    {
        "id": 0,
        "name": "Item 0",
        "price": "$0"
    },
    {
        "id": 1,
        "name": "Item 1",
        "price": "$1"
    },
    {
        "id": 2,
        "name": "Item 2",
        "price": "$2"
    }
]

这是服务端分页的数据结构:

{
    "total": 200,
    "rows": [
        {
            "id": 0,
            "name": "Item 0",
            "price": "$0"
        },
        {
            "id": 1,
            "name": "Item 1",
            "price": "$1"
        },
        {
            "id": 2,
            "name": "Item 2",
            "price": "$2"
        }
    ]
}

这是因为客户端来分页的话,他直接根据数据总量进行判断要分成多少页,而服务端的话就需要返回一个total给他,因为服务端返回给的数据是一个片段,他没办法根据这个片段来计算多少页。

注意:这里可以看到,服务端分页和客户端分页数据结构的层次是不同的。他接受哪种数据结构,取决于是否加这个参数:

sidePagination:'server'

特别是做子表的时候,因为觉得没有做分页的必要,就没了这句话,结果就是数据过去了死活不显示,排查很久才发现是这个问题。

4、参数上传

我们知道,当我们对table设置一个url的时候,他不仅是请求这个url,他还会带一些参数上来,他到底带来了什么参数?

我们来一个最简单的测试一下:

        $('#table').bootstrapTable({
            striped: true,
            pagination:true,
            sidePagination:'server',
            url:'/xx/yy',
            columns: [{
                field: 'id',
                title: 'Item ID'
            }, {
                field: 'name',
                title: 'Item Name'
            }, {
                field: 'price',
                title: 'Item Price'
            }]
        });


这里我们简单的初始化了一个bootstrap-table,数据来源我们指定了url,有个参数叫method,默认是'get',也可以设为'post',如果实际上线最好设为'post',但是这里我们就用默认的好了,可以直接在浏览器的控制台看到他请求的参数。


我们可以看到带了一些参数上来

(1)order=asc表示排序是升序排序,这个我们可以在参数里面设置:sortOrder: "asc/desc"(两种选一种)

(2)offset=0表示从数据从哪个row开始,简单的说从第几行数据开始

(3)limit=10表示选取多少个数据,也就是一页有多少条数据

2,3跟参数pageNumber和pageSize是紧密关联的。

pageSize对应的就是limit,因此改变pageSize就改变了limit;

pageNumber结合pageSize可以算出offset。

比如pageNumber=1,pageSize=30,那么offset=0,limit=30;

比如pageNumber=2,pageSize=30,那么offset=30,limit=30。

他不传第几页上来,而是传从第几行开始,选取多少行,这样一个数据。

注意:pageNumber从1开始而非从0开始,但是offset是从0开始的。

如果我尝试设置pageNumber:0,pageSize:30我们会发现offset=-30,limit=30,这是不对的。

5、参数的查看、修改

那么我们可以直接查看这些参数以及修改吗?答案是可以的。

有个原始参数就是用来配置这个:

queryParams:testQParams

创建函数:

function testQParams(params) {
            alert('params.limit='+params.limit+' params.offset='+params.offset);//我们可以这样查看这些要上传的参数
        }

我们当然可以修改或者添加参数:

        function testQParams(params) {
            return {
                limit:params.limit,
                offset:params.offset,
                order:params.order,
                abc:123,
                def:456
            }
        }

有几点要注意:

1、我们当然可以修改limit、offset这些参数,但是不建议在这里改,我们可以用上面这种方式还给他赋值;

2、虽然没有改动他,我们也不要丢了,如果在这里没写参数就丢了,传递的参数会以这里的为准;

3、我们可以增加新的参数。


七、显示图片

字段通常是一个地址,那么我们要显示图片应该使用formatter:

{
                field: 'thumb_img',
                title: '主图',
                align: 'center',
                formatter:function (value,row,index) {
                    return '<img  class="img-rounded lazy" src="/static/imghwm/default1.png" data-src="<?php echo '/static/bootstrap/extensions/editable/js/bootstrap-editable.js'; ?>" alt="Summary of the use of bootstrap-table in BootStrap" >';
                }
            }

可以直接定义宽度,图片会自动进行缩放。

八、行内编辑功能

bootstrap-editable

需要一个bootstrap插件叫做bootstrap-editable,现在改名叫做x-editable了,可以适用不同的框架。

地址:https://github.com/vitalets/x-editable

下载下来之后,找到dist/bootstrap3-editable里面的3个文件夹css,js,img都拷贝到我们的网站目录下。

bootstrap-table-editable

这是一个bootstrap-table的插件(插件的插件),这个插件呢就在我们下载的bootstrap-table包里,路径是dist/extensions/editable

把他拷到我们的对应目录下即可

引入
<link>" rel="stylesheet">
<script></script>
<script>"></script>

注意他们跟jquery、bootstrap、bootstrap-table的依赖关系,所以要放在他们的后面。

使用1:

在列定义里面加上editable:true,比如:

                field:'addr',
                title:'地址',
                editable:true,

就会变成可编辑状态了

使用2:

编辑完成我们要添加一个回调

在bootstrapTable顶级的属性定义里面,添加一个回调函数:

            onEditableSave:function (field,row,oldValue,$el) {
                //alert('保存addr='+row.addr+' id='+row.itemid);
            }


这里我们可以看到当编辑完保存的时候就会调用到这个函数,在row里面有所有当前行的信息,那么我们可以通过把这个信息用ajax传递到服务器保存起来。

编辑功能完成。

保存验证+ajax保存确认+取消保存

我们在实际开发当中,经常需要这样的功能:

(1)验证用户的输入是否正确;

(2)如果用户输入不正确,就不要在页面上显示了,直接显示保存不了;

(3)如果用户输入正确,通过ajax请求保存到后台;

(4)如果保存到后台失败,应该返回前端失败的消息,前端的内容回退到保存前的状态;

(5)如果保存成功,前端也做相应的显示样式调整及状态确定。

在上面“使用1”及“使用2”当中,当点击保存的时候,在save函数里验证不起作用,你再验证他也保存进去了。所以验证另有地方。

应该这样做:

(1)把editable:true改为:
                    validate:function (value) {
                        value = $.trim(value);
                        if (!value)
                        {
                            return '必须填入一个网址,不能放空!';
                        }
                        if (!checkUrl(value))
                        {
                            return '输入的不是一个合法的网址!';
                        }

                    }

另外,在这个函数里,要取的row数据可以这样:

                        var data = $('#table').bootstrapTable('getData');
                        var index = $(this).parents('tr').data('index');
                        console.log(data[index]);

这是因为这个$(this)可以指向这个当前单元格

这样输入就有验证功能,return一个字符串他会自动不保存进去,而显示这个字符串的提示。

注意,验证的保存规则:

如果return '';  则会保存空字符串;

如果return 'xxx';  则不会保存这个字符串,而是作为提示显示出来;

如果不return,则按照原value保存。

(2)把onEditableSave改为:
                onEditableSave:function (field,row,oldValue,$el) {
                    // 测试证明oldValue取到的是undefined
                    $.post('xxx/yyy')
                        .done(function (result) {
                            //在这里解析result
                            if(保存成功)
                            {
                                // 页面提示保存成功
                            }else
                            {
                                // 页面提示保存失败
                                // buy_addr_bak这个字段是从服务端传过来与buy_addr等值的一个字段,就是为了在必要的时候恢复数据
                                $el.text(row.buy_addr_bak);
                            }
                            // 不管保存成功还是失败,已经不是编辑状态,把加粗去掉
                            $el.removeClass('editable-unsaved');
                        });
                }

另外,在这个函数里,如果要取到row数据可以这样(虽然这里没有必要,参数里已经有了):

                var data = $('#table').bootstrapTable('getData');
                var index = $el.parent().parents('tr').data('index');//注意这里一个是parent,一个是parents
                console.log(data[index]);

九、自动换行

在给table加上样式:

style="word-break:break-all; word-wrap:break-all;"

十、父子表

功能:点击行首的加号,下拉展开一个子表

在父表的属性里添加

detailView:true

添加回调函数

                onExpandRow:function (index,row,$detail) {
                    initSubTable(index,row,$detail);
                }

当点击行首的加号,将会触发这个回调函数,这个回调函数会再去调用执行函数。

执行函数

        function initSubTable(index,row,$detail) {
            var parentid = row.MENU_ID;
            var cur_table = $detail.html('
').find('table');//注意这个'table'不是一个id,他在任何情况下不需要改变             $(cur_table).bootstrapTable({                 url:'',                 method:'post',                 queryParams:{strParentID:parentid},                 ajaxOptions:{strParentID:parentid},                 clickToSelect:true,                 detailView:true,                 uniqueId:"MENU_ID",                 pageSize:10,                 pageList:[10,25],                 columns:[                     {                         filed:'from',                         title:'from'                     },                     {                         field:'url',                         title:'url'                     },                     {                         field:'to',                         title:'to'                     }                 ],                 onExpandRow:function (index,row,$Subdetail) {                     initSubTable(index,row,$Subdetail);                 }             });         }

注意,这里做了一个递归,即子表里面还可以展开孙表,我们也可以不需要,去掉就可以了。

十一、刷新功能

$('#table_search').bootstrapTable(
                    "refresh",
                    {
                        url:"/japp/autobuy/ajaxorder/search"
                    }
                );

总结:以上就是本篇文的全部内容,希望能对大家的学习有所帮助。

The above is the detailed content of Summary of the use of bootstrap-table in BootStrap. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:CSDN. If there is any infringement, please contact admin@php.cn delete
Beyond the Browser: JavaScript in the Real WorldBeyond the Browser: JavaScript in the Real WorldApr 12, 2025 am 12:06 AM

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.

Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Apr 11, 2025 am 08:23 AM

I built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing

How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration)How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration)Apr 11, 2025 am 08:22 AM

This article demonstrates frontend integration with a backend secured by Permit, building a functional EdTech SaaS application using Next.js. The frontend fetches user permissions to control UI visibility and ensures API requests adhere to role-base

JavaScript: Exploring the Versatility of a Web LanguageJavaScript: Exploring the Versatility of a Web LanguageApr 11, 2025 am 12:01 AM

JavaScript is the core language of modern web development and is widely used for its diversity and flexibility. 1) Front-end development: build dynamic web pages and single-page applications through DOM operations and modern frameworks (such as React, Vue.js, Angular). 2) Server-side development: Node.js uses a non-blocking I/O model to handle high concurrency and real-time applications. 3) Mobile and desktop application development: cross-platform development is realized through ReactNative and Electron to improve development efficiency.

The Evolution of JavaScript: Current Trends and Future ProspectsThe Evolution of JavaScript: Current Trends and Future ProspectsApr 10, 2025 am 09:33 AM

The latest trends in JavaScript include the rise of TypeScript, the popularity of modern frameworks and libraries, and the application of WebAssembly. Future prospects cover more powerful type systems, the development of server-side JavaScript, the expansion of artificial intelligence and machine learning, and the potential of IoT and edge computing.

Demystifying JavaScript: What It Does and Why It MattersDemystifying JavaScript: What It Does and Why It MattersApr 09, 2025 am 12:07 AM

JavaScript is the cornerstone of modern web development, and its main functions include event-driven programming, dynamic content generation and asynchronous programming. 1) Event-driven programming allows web pages to change dynamically according to user operations. 2) Dynamic content generation allows page content to be adjusted according to conditions. 3) Asynchronous programming ensures that the user interface is not blocked. JavaScript is widely used in web interaction, single-page application and server-side development, greatly improving the flexibility of user experience and cross-platform development.

Is Python or JavaScript better?Is Python or JavaScript better?Apr 06, 2025 am 12:14 AM

Python is more suitable for data science and machine learning, while JavaScript is more suitable for front-end and full-stack development. 1. Python is known for its concise syntax and rich library ecosystem, and is suitable for data analysis and web development. 2. JavaScript is the core of front-end development. Node.js supports server-side programming and is suitable for full-stack development.

How do I install JavaScript?How do I install JavaScript?Apr 05, 2025 am 12:16 AM

JavaScript does not require installation because it is already built into modern browsers. You just need a text editor and a browser to get started. 1) In the browser environment, run it by embedding the HTML file through tags. 2) In the Node.js environment, after downloading and installing Node.js, run the JavaScript file through the command line.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.