js插件---JS表格組件BootstrapTable行內編輯解決方案x-editable


js插件---JS表格組件BootstrapTable行內編輯解決方案x-editable

一、總結

一句話總結:bootstrap能夠做為最火的框架,絕對不僅僅只有我看到的位置,它應該還有很多位置可以極大的方便開發,可能是插件這一塊,也可能是別的。

 

1、創建可編輯彈出框的插件叫什么?

x-editable組件

 

2、bootstrap Table的優勢是什么?

在開發經歷中,也使用Jqgrid、EasyUI等表格組件。相比而言,bootstrap Table有自己的優勢:

1、界面采用扁平化的風格,用戶體驗比較好,更好兼容各種客戶端。這點也是最重要的。

2、開源、免費。國人最喜歡的就是免費了。呵呵。

3、相對Jqgrid、easyUI而言,比較輕量級。功能不能說最全面,但基本夠用。

 

 

 

二、JS表格組件BootstrapTable行內編輯解決方案x-editable

前言:之前介紹bootstrapTable組件的時候有提到它的行內編輯功能,只不過為了展示功能,將此一筆帶過了,罪過罪過!最近項目里面還是打算將行內編輯用起來,於是再次研究了下x-editable組件,遇到過一些坑,再此做個采坑記錄吧!想要了解bootstrapTable的朋友可以移步JS組件系列——表格組件神器:bootstrap table。 

一、x-editable組件介紹 

x-editable組件是一個用於創建可編輯彈出框的插件,它支持三種風格的樣式:bootstrap、Jquery UI、Jquery。大致效果如下圖: 

根據博主一貫的風格,這里肯定是選用第一種嘍。首先還是給出開源地址吧。 
x-editable開源地址:https://github.com/vitalets/x-editable 
x-editable文檔地址:http://vitalets.github.io/x-editable/docs.html 
x-editable在線Demo:http://vitalets.github.io/x-editable/demo-bs3.html 

 1、x-editable初體驗 

首先下載基於bootstrap的源碼到本地。引用相關文件。 

?
1
2
3
4
5
6
< link href = "/Content/bootstrap/css/bootstrap.min.css" rel = "stylesheet" />
< link href = "~/Content/bootstrap3-editable/css/bootstrap-editable.css" rel = "stylesheet" />
  
< script src = "/Scripts/jquery-1.9.1.min.js" ></ script >
< script src = "/Content/bootstrap/js/bootstrap.min.js" ></ script >
< script src = "~/Content/bootstrap3-editable/js/bootstrap-editable.js" ></ script >

 頁面元素

復制代碼 代碼如下:
<a href="#" id="username" data-type="text" data-title="用戶名">用戶名</a>

 

js初始化

?
1
2
3
$( function () {
  $( '#username' ).editable();
});

效果展示

 

上面是通過html的data屬性去設置x-editable的參數,當然,我也可以在初始化的時候去設置參數,比如,我僅僅給一個空的a標簽:<a href="#" id="username">用戶名</a>

js初始化 

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
$( function () {
  $( '#username' ).editable({
   type: "text" ,    //編輯框的類型。支持text|textarea|select|date|checklist等
   title: "用戶名" ,    //編輯框的標題
   disabled: false ,    //是否禁用編輯
   emptytext: "空文本" ,   //空值的默認文本
   mode: "inline" ,    //編輯框的模式:支持popup和inline兩種模式,默認是popup
   validate: function (value) { //字段驗證
    if (!$.trim(value)) {
     return '不能為空' ;
    }
   }
  });
 
});

查看效果

 

再來個稍微復雜一點的
 <a href="#" id="department">選擇部門</a>

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
$( function () {
  $( '#department' ).editable({
   type: "select" ,    //編輯框的類型。支持text|textarea|select|date|checklist等
   source: [{ value: 1, text: "開發部" }, { value: 2, text: "銷售部" }, {value:3,text: "行政部" }],
   title: "選擇部門" ,   //編輯框的標題
   disabled: false ,   //是否禁用編輯
   emptytext: "空文本" //空值的默認文本
   mode: "popup" ,   //編輯框的模式:支持popup和inline兩種模式,默認是popup
   validate: function (value) { //字段驗證
    if (!$.trim(value)) {
     return '不能為空' ;
    }
   }
  });
 
});

查看效果

 

上文只是給出了一些常用字段,當然x-editable組件還有很多其他的功能參數,有興趣可以看看文檔,官方文檔對每個參數都有詳細的說明。 

二、bootstrapTable行內編輯初始方案 

說了這么半天,上面的只是鋪墊,我們最終是希望在bootstrapTable里面實現行內編輯。根據上面的規則,我們想要使用x-editable實現行內編輯,表格的單元格里面必須要有一個a標簽,然后對a標簽做x-editable的初始化。有了這個想法,我們按照這種思路先試試。 

引用相關文件 

?
1
2
3
4
5
6
7
8
9
< link href = "/Content/bootstrap/css/bootstrap.min.css" rel = "stylesheet" />
< link href = "~/Content/bootstrap3-editable/css/bootstrap-editable.css" rel = "stylesheet" />
< link href = "/Content/bootstrap-table/bootstrap-table.min.css" rel = "stylesheet" />
  
< script src = "/Scripts/jquery-1.9.1.min.js" ></ script >
< script src = "/Content/bootstrap/js/bootstrap.min.js" ></ script >
< script src = "~/Content/bootstrap3-editable/js/bootstrap-editable.js" ></ script >
< script src = "~/Content/bootstrap-table/bootstrap-table.js" ></ script >
< script src = "/Content/bootstrap-table/locale/bootstrap-table-zh-CN.js" ></ script >

bootstrapTable的相關初始化 

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
<script type= "text/javascript" >
  var curRow = {};
  $( function () {
   $( "#tb_user" ).bootstrapTable({
    toolbar: "#toolbar" ,
    idField: "Id" ,
    pagination: true ,
    showRefresh: true ,
    search: true ,
    clickToSelect: true ,
    queryParams: function (param) {
     return {};
    },
    url: "/Editable/GetUsers" ,
    columns: [{
     checkbox: true
    }, {
     field: "UserName" ,
     title: "用戶名" ,
     formatter: function (value, row, index) {
      return "<a href=\"#\" name=\"UserName\" data-type=\"text\" data-pk=\"" +row.Id+ "\" data-title=\"用戶名\">" + value + "</a>" ;
     }
    }, {
     field: "Age" ,
     title: "年齡" ,
    }, {
     field: "Birthday" ,
     title: "生日" ,
     formatter: function (value, row, index) {
      var date = eval( 'new ' + eval(value).source)
      return date.format( "yyyy年MM月dd日" );
     }
    },
    {
     field: "DeptName" ,
     title: "部門"
    }, {
     field: "Hodd" ,
     title: "愛好"
    }],
    onClickRow: function (row, $element) {
     curRow = row;
    },
    onLoadSuccess: function (aa, bb, cc) {
     $( "#tb_user a" ).editable({
      url: function (params) {
       var sName = $( this ).attr( "name" );
       curRow[sName] = params.value;
       $.ajax({
        type: 'POST' ,
        url: "/Editable/Edit" ,
        data: curRow,
        dataType: 'JSON' ,
        success: function (data, textStatus, jqXHR) {
         alert( '保存成功!' );
        },
        error: function () { alert( "error" );}
       });
      },
      type: 'text'
     });
    },
   });
  });</script>

后台方法 

后台測試方法

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
public JsonResult GetUsers()
   {
    var lstRes = new List<User>();
    lstRes.Add( new User() { Id = "1" , UserName = "張三" , Age = 22 , Birthday = Convert.ToDateTime( "1994-12-21" ), DeptId = "1" , DeptName = "研發部" });
    lstRes.Add( new User() { Id = "2" , UserName = "李四" , Age = 28 , Birthday = Convert.ToDateTime( "1988-09-09" ), DeptId = "2" , DeptName = "銷售部" });
    lstRes.Add( new User() { Id = "3" , UserName = "風衣大叔" , Age = 40 , Birthday = Convert.ToDateTime( "1976-09-01" ), DeptId = "2" , DeptName = "銷售部" });
    lstRes.Add( new User() { Id = "4" , UserName = "閃電大蝦" , Age = 37 , Birthday = Convert.ToDateTime( "1979-03-12" ), DeptId = "4" , DeptName = "創意部" });
    lstRes.Add( new User() { Id = "5" , UserName = "韓梅梅" , Age = 29 , Birthday = Convert.ToDateTime( "1987-05-01" ), DeptId = "5" , DeptName = "事業部" });
  
    return Json(lstRes, JsonRequestBehavior.AllowGet);
   }
  
   public JsonResult Edit(User user)
   {
    //反序列化之后更新
  
    return Json( new { }, JsonRequestBehavior.AllowGet);
   }

這樣確實是可以實現想要的效果,貌似也能行內編輯了,可是如果沒個列都需要行內編輯,並且列的個數很多,那么是不是每個列都得這樣去formmater?並且這種寫法狠顯然很死板,博主着實難以接受。於是又找了找例子,發現在bootstrapTable的擴展里面存在bootstrap-table-editable.js這個js。 

三、bootstrapTable行內編輯最終方案 

好吧,博主承認,上面還是鋪墊,因為博主覺得這可能是解決問題的一般思路,所以將這些鋪墊的篇幅可能有點多。首先來看看bootstrap-table-editable.js這個文件:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
/**
  * @author zhixin wen <wenzhixin2010@gmail.com>
  */
  
! function ($) {
  
  'use strict' ;
  
  $.extend($.fn.bootstrapTable.defaults, {
   editable: true ,
   onEditableInit: function () {
    return false ;
   },
   onEditableSave: function (field, row, oldValue, $el) {
    return false ;
   },
   onEditableShown: function (field, row, $el, editable) {
    return false ;
   },
   onEditableHidden: function (field, row, $el, reason) {
    return false ;
   }
  });
  
  $.extend($.fn.bootstrapTable.Constructor.EVENTS, {
   'editable-init.bs.table' : 'onEditableInit' ,
   'editable-save.bs.table' : 'onEditableSave' ,
   'editable-shown.bs.table' : 'onEditableShown' ,
   'editable-hidden.bs.table' : 'onEditableHidden'
  });
  
  var BootstrapTable = $.fn.bootstrapTable.Constructor,
   _initTable = BootstrapTable.prototype.initTable,
   _initBody = BootstrapTable.prototype.initBody;
  
  BootstrapTable.prototype.initTable = function () {
   var that = this ;
   _initTable.apply( this , Array.prototype.slice.apply(arguments));
  
   if (! this .options.editable) {
    return ;
   }
  
   $.each( this .columns, function (i, column) {
    if (!column.editable) {
     return ;
    }
  
    var _formatter = column.formatter;
    column.formatter = function (value, row, index) {
     var result = _formatter ? _formatter(value, row, index) : value;
  
     return [ '<a href="javascript:void(0)"' ,
      ' data-name="' + column.field + '"' ,
      ' data-pk="' + row[that.options.idField] + '"' ,
      ' data-value="' + result + '"' ,
      '>' + '</a>'
     ].join( '' );
    };
   });
  };
  
  BootstrapTable.prototype.initBody = function () {
   var that = this ;
   _initBody.apply( this , Array.prototype.slice.apply(arguments));
  
   if (! this .options.editable) {
    return ;
   }
  
   $.each( this .columns, function (i, column) {
    if (!column.editable) {
     return ;
    }
  
    that.$body.find( 'a[data-name="' + column.field + '"]' ).editable(column.editable)
     .off( 'save' ).on( 'save' , function (e, params) {
      var data = that.getData(),
       index = $( this ).parents( 'tr[data-index]' ).data( 'index' ),
       row = data[index],
       oldValue = row[column.field];
  
      row[column.field] = params.submitValue;
      that.trigger( 'editable-save' , column.field, row, oldValue, $( this ));
     });
    that.$body.find( 'a[data-name="' + column.field + '"]' ).editable(column.editable)
     .off( 'shown' ).on( 'shown' , function (e, editable) {
      var data = that.getData(),
       index = $( this ).parents( 'tr[data-index]' ).data( 'index' ),
       row = data[index];
       
      that.trigger( 'editable-shown' , column.field, row, $( this ), editable);
     });
    that.$body.find( 'a[data-name="' + column.field + '"]' ).editable(column.editable)
     .off( 'hidden' ).on( 'hidden' , function (e, reason) {
      var data = that.getData(),
       index = $( this ).parents( 'tr[data-index]' ).data( 'index' ),
       row = data[index];
       
      that.trigger( 'editable-hidden' , column.field, row, $( this ), reason);
     });
   });
   this .trigger( 'editable-init' );
  };
  
}(jQuery);

這個js其實是對x-editable做了一個簡單的封裝,增加了列的editable屬性以及編輯保存后的一些事件。有了這個作為基礎,於是我們行內編輯的代碼變成了這樣。

需要引用的文件如下: 

?
1
2
3
4
5
6
7
8
9
10
< link href = "/Content/bootstrap/css/bootstrap.min.css" rel = "stylesheet" />
< link href = "~/Content/bootstrap3-editable/css/bootstrap-editable.css" rel = "stylesheet" />
< link href = "/Content/bootstrap-table/bootstrap-table.min.css" rel = "stylesheet" />
  
< script src = "/Scripts/jquery-1.9.1.min.js" ></ script >
< script src = "/Content/bootstrap/js/bootstrap.min.js" ></ script >
< script src = "~/Content/bootstrap3-editable/js/bootstrap-editable.js" ></ script >
< script src = "~/Content/bootstrap-table/bootstrap-table.js" ></ script >
< script src = "/Content/bootstrap-table/locale/bootstrap-table-zh-CN.js" ></ script >
< script src = "~/Content/bootstrap-table/extensions/editable/bootstrap-table-editable.js" ></ script >

1、文本框 

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
  $( function () {
   $( "#tb_user" ).bootstrapTable({
    toolbar: "#toolbar" ,
    idField: "Id" ,
    pagination: true ,
    showRefresh: true ,
    search: true ,
    clickToSelect: true ,
    queryParams: function (param) {
     return {};
    },
    url: "/Editable/GetUsers" ,
    columns: [{
     checkbox: true
    }, {
     field: "UserName" ,
     title: "用戶名" ,
     editable: {
      type: 'text' ,
      title: '用戶名' ,
      validate: function (v) {
       if (!v) return '用戶名不能為空' ;
  
      }
     }
    }, {
     field: "Age" ,
     title: "年齡" ,
    }, {
     field: "Birthday" ,
     title: "生日" ,
     formatter: function (value, row, index) {
      var date = eval( 'new ' + eval(value).source)
      return date.format( "yyyy-MM-dd" );
     }
    },
    {
     field: "DeptName" ,
     title: "部門"
    }, {
     field: "Hobby" ,
     title: "愛好"    
    }],
    onEditableSave: function (field, row, oldValue, $el) {
     $.ajax({
      type: "post" ,
      url: "/Editable/Edit" ,
      data: row,
      dataType: 'JSON' ,
      success: function (data, status) {
       if (status == "success" ) {
        alert( '提交數據成功' );
       }
      },
      error: function () {
       alert( '編輯失敗' );
      },
      complete: function () {
  
      }
  
     });
    }
   });
  });

后台對應的更新方法

?
1
2
3
4
5
6
public JsonResult Edit(User user)
{
  //更新實體
 
  return Json( new { }, JsonRequestBehavior.AllowGet);
}

經過測試,用戶名這一列基本可以自由編輯。同樣,年齡這一列也可改成這樣 

?
1
2
3
4
5
6
7
8
9
10
11
12
13
       {
     field: "Age" ,
     title: "年齡" ,
     editable: {
      type: 'text' ,
      title: '年齡' ,
      validate: function (v) {
       if (isNaN(v)) return '年齡必須是數字' ;
       var age = parseInt(v);
       if (age <= 0) return '年齡必須是正整數' ;
      }
     }
    }

其他基本不用做任何修改。
 代碼釋疑:上文在初始化的columns屬性里面通過editable屬性來配置可編輯的參數,注意這里每個列的editable屬性對應的Json對象即為x-editable里面的初始化的Json對象,也就是說我們初始化x-editable的時候可以配置哪些屬性,在列的editable屬性里面也可以同樣配置,這樣用起來就爽多了吧。編輯后的提交方法統一放到onEditableSave事件里面統一處理。

2、時間選擇框

有了上面的知識作為基礎,我們來初始化生日這一列: 

?
1
2
3
4
5
6
7
8
9
10
11
12
{
  field: "Birthday" ,
  title: "生日" ,
  formatter: function (value, row, index) {
   var date = eval( 'new ' + eval(value).source)
   return date.format( "yyyy-MM-dd" );
  },
  editable: {
   type: 'date' ,
   title: '生日'
  }
}

其他地方不用做任何修改,得到效果: 

這是x-editable的默認樣式,如果你看着不爽,可以自行配置,x-editable提供了許多配置日期框的參數,如下: 

當然,如果精確到時分秒,可以使用datetime類型的編輯框。如下是官方給出的時間框編輯效果,看着還不錯。

 

3、下拉框 

表單編輯里面還有一個重要的標簽就是select了。上文我們知道x-editable為我們提供了下拉框的編輯模式,比如我們的部門這一列的編輯可以寫成這樣: 

?
1
2
3
4
5
6
7
8
9
       {
     field: "DeptId" ,
     title: "部門" ,
     editable: {
      type: 'select' ,
      title: '部門' ,
      source:[{value: "1" ,text: "研發部" },{value: "2" ,text: "銷售部" },{value: "3" ,text: "行政部" }]
     }
    }

得到效果

 

當然,這種本地設置數據源的方法肯定是不能滿足我們需求的,因為很多情況下拉框里面的選項是從數據庫遠程得到的。當然x-editable也為我們考慮到了,比如我們可以這樣寫: 

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
{
     field: "DeptId" ,
     title: "部門" ,
     editable: {
      type: 'select' ,
      title: '部門' ,
      source: function () {
       var result = [];
       $.ajax({
        url: '/Editable/GetDepartments' ,
        async: false ,
        type: "get" ,
        data: {},
        success: function (data, status) {
         $.each(data, function (key, value) {
          result.push({ value: value.ID, text: value.Name });
         });
        }
       });
       return result;
      }
     }
    }

后台我們配置一個方法 

?
1
2
3
4
5
6
7
8
9
10
public JsonResult GetDepartments()
{
  var lstRes = new List<Department>();
  lstRes.Add( new Department() { ID = "1" , Name = "研發部" });
  lstRes.Add( new Department() { ID = "2" , Name = "銷售部" });
  lstRes.Add( new Department() { ID = "3" , Name = "行政部" });
  lstRes.Add( new Department() { ID = "4" , Name = "創意部" });
  lstRes.Add( new Department() { ID = "5" , Name = "事業部" });
  return Json(lstRes, JsonRequestBehavior.AllowGet);
}

同樣能達到我們想要的結果。 

代碼釋疑:這里有一點需要說明一下,細心的園友可能發現了,我們這里的 field: "DeptId" ,為什么這里要配置DeptId而不是DeptName呢?很簡單,因為我們需要和數據源里面的value值對應。 

4、復選框

除了上述幾種常見的編輯框,x-editable還為我們提供了復選框組的編輯。比如: 

?
1
2
3
4
5
6
7
8
9
10
11
{
     field: "Hobby" ,
     title: "愛好" ,
     editable: {
      type: "checklist" ,
      separator: "," ,
      source: [{ value: 'bsb' , text: '籃球' },
        { value: 'ftb' , text: '足球' },
        { value: 'wsm' , text: '游泳' }],
     }
    }

得到效果:

 

當然,如果遠程數據,也可以使用類似上文的方法去取。 

5、“陰魂不散”的select2 

說到上文的復選框,博主不由自主又想到了Multiselect這些個東西,於是查找x-editable的文檔,結果發現它不支持Multiselect,但是支持select2,也不知道這是不是一個好消息。根據博主自己的使用經歷,也包括技術交流群里面的聊天經歷,發現很多人在使用select2的時候都遇到過各種各樣的樣式問題,並且不太好解決。 

既然x-editable支持select2,那我們就用用試試唄,反正官方demo說得挺好的,下面是官方demo的使用示例:

 

懷着忐忑的心情,博主自己嘗試了一把。 

引用select2文件

?
1
2
3
< link href = "~/Content/select2-bootstrap.css" rel = "stylesheet" />
< link href = "~/Content/select2-master/dist/css/select2.min.css" rel = "stylesheet" />
< script src = "~/Content/select2-master/dist/js/select2.full.min.js" ></ script >

代碼嘗試 

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
{
     field: "Hobby" ,
     title: "愛好" ,
     editable: {
      type: 'select2' ,
      title: '愛好' ,
      name: 'Hobby' ,
      placement: 'top' ,
      success: function (response, newValue) {
       debugger;
      },
      error: function (response, newValue) {
       debugger;
      },
      url: function (params) {
       debugger;
      },
      source: [{ id: 'bsb' , text: '籃球' },
         { id: 'ftb' , text: '足球' },
         { id: 'wsm' , text: '游泳' }],
      inputclass: 'input-large' ,
      select2: {
       allowClear: true ,
       multiple: true ,
     
     }
    }

得到結果:

結果發現select2的選中值不能正常傳遞到后台。反正博主試過各種參數,按照官方demo的寫法也試過,均以失敗告終。也不知道官方的demo如何成功的。這個問題先拋出來,如果有使用的園友歡迎指正與解答。后續如果博主解決了這個問題,也會在此更新。  

四、總結 

還有一個問題就是在編輯完成提交之后,博主在項目中遇到這樣一個問題:如果提交之后的文本內容過多,表格的thead里面th的寬度和tbody里面td的寬度不對其的問題,看着相當惡心。但是在寫demo的時候又沒有遇到這個問題。在此還是將解決方案給出來。

 

就這么一句話解決你的困擾!

 

參考:JS表格組件BootstrapTable行內編輯解決方案x-editable_javascript技巧_腳本之家
https://www.jb51.net/article/91708.htm

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM