Bootstrap table use method to parse _javascript skills

Source: Internet
Author: User
Tags locale

Some of the things in jquery learn all of a sudden, to complement, after all, sometimes not used to
This is useful, when using bootstrap table, select the value of the ID in the event of the node that is currently selected
There is a lot of data in the current rows, but I just need the ID for this one value and it's very easy to do this at this point.

$.map (Data,function (item,index) {return XXX})
//Usage Summary:
 //Put an array in the new way to assemble the returned, unlike the original array.
 //Iterate through each element of the data array and form a new element in the calculation of return, putting the returned array
 var b = $.map ([55,1,2], function (item,index) { 
 return { 
 "label": Item,
 "value": Index 
 }
 });
 Alert (B[0].label + "" + b[0].value); 
 Output is 55 0 

2. My backstage, is uses SPRINGMVC to carry on the writing, during it also encountered many problems, carries on the paging processing time
I use an offline query , but I use the Execute () method, the incoming session is the proxy class data, and it can't be converted in the following method
caused the error, I also Baidu for a long time, finally found that the problem caused by

/** * Get a executable instance of <literal>criteria</literal>, * to actually run the query. * * Public
 Criteria Getexecutablecriteria (Sessions session) {
 impl.setsession (sessionimplementor) ;
 return impl;
 }
Return (Pagebean) gethibernatetemplate (). Executewithnativesession (New Hibernatecallback () {public
 Object Doinhibernate (Session session) throws Hibernateexception {
 criteria = Detachedcriteria.getexecutablecriteria (session);
 ............................
 }

Backstage, I returned the data and format is not according to the format of the bootstrap a little different, anyway, is not the same

{
 "Success": True,
 "message": null,
 "data": {
 "pageSize": "
 Rows": [

 {
 ] UserName ":" 333 ","
 usertype ": 333,
 " password ":" 333 ",
 " id ": One,
 " Indexcode ":" 333 "
 },
 {
 "UserName": "3", "
 usertype": 333,
 "password": "333",
 "id": 5,
 "Indexcode": "33333"
 }
 ...
 ],
 "Total": "
 totalpage": 2,
 "page": 0, "
 haspreviouspage": True,
 " Hasnextpage ': True,
 ' lastpage ': false,
 ' FirstPage ': false
 }
}

Mainly here I am using a unified return interface ActionResult, so that the more convenient writing format, unified back end

* *
 Created by Jetwang on 2016/10/1.
 * * Public
class ActionResult {

 private Boolean success;

 private String message;

 Private Object data;


 Public ActionResult () {
 } public

 ActionResult (Boolean success) {This
 (success, NULL, NULL);
 }

 ............

}

Let's look at the front end effect.

Front-end pages

<%@ include file= "./common/common.jsp"%>//What common bootstrapt, jquery, and the like are put in the process
<script src= "<%= Baseurl%>/libs/bootstrap-table/dist/bootstrap-table.js "type=" Text/javascript "></script>
< Script src= "<%=baseurl%>/libs/bootstrap-table/dist/bootstrap-table-locale-all.js" type= "Text/javascript" > </script>
<link rel= "stylesheet" href= "<%=baseurl%>/libs/bootstrap-table/dist/ Bootstrap-table.css "type=" text/css ">
//This is the
<div class=" container ">
 <table ID where the table is placed in the container = "Table" data-url= "/cms/userinfo/userinfopage" >//used path, background request URL
 </table>
</div>

Description of the more important JS code

JQuery (document). Ready (function () {
 ///Here you can use a variety of wizards, you can also use the SEAJS front-end modular tool to
 place our JS code is good
});

The following configuration file and some overrides of the event, you can look at the document, or go to your own source
Here you can rewrite Oh ~ ~, EXTENTD for a new cover!

Bootstraptable.defaults = {classes: ' Table Table-hover ', locale:undefined, height:undefined, Undefinedtext: '-', sortname:undefined, SortOrder: ' ASC ', Sortstable:false, Striped:false, Columns: [[]], data: [], DataField: ' Rows ' , method: ' Get ', url:undefined, ajax:undefined, Cache:true, ContentType: ' Application/json;charset=utf-8 ',//Here I add A utf-8 dataType: ' JSON ', ajaxoptions: {}, Queryparams:function (params) {//This is to set the parameters of the query, I directly modified in the source code, do not like offetset I use the background is PageNo.
 This processing on the comparison to meet my requirements, in fact, can also be changed in the background, trouble!
 return params; }, Queryparamstype: ' Limit ',//undefined (here is the criteria for selecting different queries based on different parameters) Responsehandler:function (res) {//Here I look at the source, the Ajax request succeeded
 After the release of data can be processed to return data, what part of the data, such as mine will need to be rectified!
 return res;  }, Pagination:false, Onlyinfopagination:false, sidepagination: ' Client ',//client or Server totalrows:0,//server
 Side need to set pagenumber:1, Pagesize:10, pagelist: [Ten, M, MB], paginationhalign: ' Right ',//right, left Paginationvalign: ' Bottom ',//bottOM, top, both paginationdetailhalign: "Left",//right, left Paginationpretext: ' ‹ ', Paginationnexttext: ' › ', search:f  Alse, Searchonenterkey:false, Strictsearch:false, searchalign: ' Right ', Selectitemname: ' Btselectitem ', ShowHeader:
 True, Showfooter:false, Showcolumns:false, showpaginationswitch:false,//the choice of the number of display pages?  Showrefresh:false, Showtoggle:false, buttonsalign: ' Right ', smartdisplay:true, Escape:false, Minimumcountcolumns: 1, idfield:undefined, uniqueid:undefined, Cardview:false, Detailview:false, detailformatter:function (Index, RO
 W) {return '; }, Trimonsearch:true, Clicktoselect:false, Singleselect:false, toolbar:undefined, toolbaralign: ' Left ', checkbox Header:true, Sortable:true, Silentsort:true, Maintainselected:false, searchtimeout:500, SearchText: ', IconSiz e:undefined, Buttonsclass: ' Default ', Iconsprefix: ' Glyphicon ',//Glyphicon of FA (font awesome) icons: {pagination Switchdown: ' Glyphicon-collapse-down ICOn-chevron-down ', Paginationswitchup: ' glyphicon-collapse-up icon-chevron-up ', refresh: ' Glyphicon-refresh Icon-refresh ', toggle: ' Glyphicon-list-alt icon-list-alt ', columns: ' glyphicon-th icon-th ', Detailopen: ' Glyphicon-plu S Icon-plus ', Detailclose: ' Glyphicon-minus icon-minus '}, Customsearch: $.noop, Customsort: $.noop, Rowstyle:fun
 ction (row, index) {return {};
 }, Rowattributes:function (row, index) {return {};
 }, Footerstyle:function (row, index) {return {};
 }, Onall:function (name, args) {return false;
 }, Onclickcell:function (field, value, row, $element) {return false;
 }, Ondblclickcell:function (field, value, row, $element) {return false;
 }, Onclickrow:function (item, $element) {return false;
 }, Ondblclickrow:function (item, $element) {return false;
 }, Onsort:function (name, order) {return false;
 }, Oncheck:function (row) {return false;
 }, Onuncheck:function (row) {return false; }, Oncheckall:function (rows) {return false;
 }, Onuncheckall:function (rows) {return false;
 }, Onchecksome:function (rows) {return false;
 }, Onunchecksome:function (rows) {return false;
 }, Onloadsuccess:function (data) {return false;
 }, Onloaderror:function (status) {return false;
 }, Oncolumnswitch:function (field, checked) {return false;
 }, Onpagechange:function (number, size) {return false;
 }, Onsearch:function (text) {return false;
 }, Ontoggle:function (CardView) {return false;
 }, Onprebody:function (data) {return false;
 }, Onpostbody:function () {return false;
 }, Onpostheader:function () {return false;
 }, Onexpandrow:function (index, row, $detail) {return false;
 }, Oncollapserow:function (index, row) {return false;
 }, Onrefreshoptions:function (options) {return false;
 }, Onrefresh:function (params) {return false;
 }, Onresetview:function () {return false;

 }
 };

Look at the above oneself also basically know how to go, write! In fact, I did not dare to play like this before, but in the course of the practice of the tutor taught me how to play, so I dare, I believe, I can play well these things!

 function inittable () {$table. bootstraptable ({striped:true,//table display stripes pagination:true,//Start paging pagesize:15,//per page display Number of records pagenumber:1,//Current page pagelist: [10, 15, 20, 25],//number of records selectable list Search:false,//Whether to enable query Showcolumns:true,//Show dropdown box Check to select The displayed column showrefresh:true,//Show Refresh button sidepagination: "Server",//indicates that the server-side request//set is undefined to get pagenumber,pagesize,searchtext , Sortname,sortorder//set for limit can get limit, offset, search, sort, order responsehandler:function (RES) {//Remote data loading before
 Handler response data format, object contains parameters: we can process the returned data format//After Ajax we can do some processing of events here return res.data; }, Queryparamstype: "Undefined", queryparams:function queryparams (params) {//Set query parameter var param = {//This is when Ajax sends the request
 Set some parameters params have something, their own look at the source code will know PageNo:params.pageNumber, pageSize:params.pageSize};
 return param;
 Execute alert ("Load succeeded" +data) onloadsuccess:function (data) {//load succeeds;
 Onloaderror:function () {////load Failed to execute layer.msg ("Load data failed", {time:1500, icon:2}); }, Height:getheight (), columns: [{field: ' state ', CHeckbox:true, align: ' center ', valign: ' Middle '}, {title: ' id ', field: ' ID ', align: ' center ', valign: ' Middle ' }, {field: ' UserName ', title: ' UserName ', sortable:true, Footerformatter:totalnameformatter, align: ' center '}, 
 {field: ' Usertype ', title: ' Usertype ', sortable:true, align: ' center '}, {field: ' Password ', title: ' Userpass ',
 Sortable:true, align: ' Center '},{field: ' Indexcode ', title: ' Indexcode ', sortable:true, align: ' center '},{ Field: ' Operate ', Title: ' Item operate ', align: ' center ', Events:operateevents, Formatter:operateformatter}]}
 ;

The Footerformatter and formatter above are the events that are handled for the display of the current column, as follows in the document
Formatter:
The context (this) is the column Object. The cell formatter function, take three parameters:value:the field value. Row:the row record data. Index:the row index.
Footerformatter:
The context (this) is the column Object. The function, take one parameter:
Data:array all of the data rows. The function should return a string with the footer cell.
are displayed for processing of the current column

The following is an increase of two buttons in a cell

 function Operateformatter (value, row, index) {return
 [' <a class= ' like ' href= ' javascript:void (0) ' title= ' like ' & gt; ', ' <i class= ' Glyphicon glyphicon-heart ' ></i> ', ' </a> ', ' <a class= ' remove ' href= ' javascript: void (0) "title=" Remove ">", ' <i class= ' Glyphicon glyphicon-remove ' ></i> ', ' </a> '].join (')
 

You can also add an event to the process here

<%--{
  title: ' Operations ',
  field: ' id ',
  align: ' center ',
  formatter:function (value,row,index) {
  var E = ' <a href= ' # "rel=" nofollow "target=" _blank "mce_href=" # "rel=" nofollow "target=" _blank "onclick=" edit (\ ' + row.id + ' \ ') ' > Edit </a> ';
  var d = ' <a href= ' # "rel=" nofollow "target=" _blank "mce_href=" # "rel=" nofollow "target=" _blank "onclick=" del (\ "+ row"). ID + ' \ ') ' > Delete </a> ';
  return e+d;
  You can also handle the event's
 }
 }--%>

The official Chinese file says the handling event can be handled as follows

The cell events listener when your use formatter function, take four parameters:event:the jQuery event. value:the field value. Row:the row record data. Index:the row index.

Example Code:

 {
 field: ' Operate ',
 title: ' Item operate ',
 align: ' center ',
 events:operateevents,
 formatter: Operateformatter
 }
 function Operateformatter (value, row, index) {return
 [' <a class= ' like ' href= ' Javascript:void (0) "title=" like ">", ' <i class= ' Glyphicon glyphicon-heart ' ></i> ', ' </a> ', ' <a class= "Remove" href= "javascript:void (0)" title= "Remove" > ", ' <i class=" Glyphicon glyphicon-remove "></i > ', ' </a> '].join (');
 }
 window.operateevents = {
 ' click ': Function (E, value, row, index) {
 alert (' Click Like Action, row: ' + Json.stringify (Row));
 },
 ' click. Remove ': function (E, value, row, index) {
 $table. bootstraptable (' Remove ', {
 field: ' ID ',
 values: [Row.id]
 };
 }
 ;

Handle the handling of events that exist in the system, which are stated in the document

$ (' #table '). Bootstraptable ({
 oneventname:function (arg1, arg2, ...) {
 // ...
 }
});

$ (' #table '). On (' Event-name.bs.table ', function (E, arg1, arg2, ...) {
 // ...
});
There are many in this name document!
Onall all.bs.table 
  name, args 
  fires when all events trigger, the parameters contain: 
  name:the event name,< C13/>args:the event data.

Handle some methods, such as how many rows are currently selected, select All, and so on

The calling method is syntax: $ (' #table '). Bootstraptable (' method ', parameter);

1 The ID of the currently selected box 
getselections none return selected rows, where no record selected, a empty array would return.

2. Select
getallselections None return all selected rows contain search or filter, when no record selected, a empty Arra Y would return.
 $table. On (' All.bs.table ', function (e, name, args) {
 console.log (name, args);
 });
3. Delete foreground data, do not need to reload
remove params remove from table in the background, the params contains two properties: 
field:the Fiel D Name of remove rows. 
Values:the array of values for rows which should is removed.

..... Lots and lots of things!
A Delete button to delete all the selected events! is not very good!

 function Getidselections () {return
 $.map ($table. bootstraptable (' getselections '), function (row) {
 return Row.id
 });
 $remove. Click (function () {
 var ids = Getidselections ();
 $table. Bootstraptable (' Remove ', {
 field: ' ID ',
 values:ids
 });
 $remove. Prop (' disabled ', true);
 };

If you want to further study, you can click here to learn, and then attach two wonderful topics: Bootstrap Learning Tutorials Bootstrap Practical course

The above is the entire content of this article, I hope to help you learn, but also hope that we support the cloud habitat community.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.