在表格顶部添加按钮的简洁方法 - Bootgrid

时间:2015-08-01 13:20:20

标签: jquery jquery-bootgrid

我正在使用Jquery-Bootgrid。 encodeURIComponent

我需要一种用户可以选择一行的情况,然后用户点击编辑/删除按钮。

我希望这可以重复使用。所以我创建了一个方法:

function dataTable() {

    var self = this;

    self.tableListUrl = "";
    self.gridObject = null;

    self.InitilizeAjaxTable = function (tableDiv, tableListUrl) {

        parameters = parameters || "";
        self.tableListUrl = tableListUrl;

        self.gridObject = $("#" + tableDiv).bootgrid({
            formatters: {
                "actions": function (column, row) {
                    return "";
                }
            },
            rowCount: [5, 10, 25, 50, -1],
            requestHandler: function (request) {

                var model = fleetMaintenance.filterModel.GetModel();
                model.Current = request.current;
                model.RowCount = request.rowCount;
                model.Search = request.searchPhrase;
                return JSON.stringify(model);
            },
            ajaxSettings: {
                method: "POST",
                contentType: "application/json"
            },
            ajax: true,
            url: self.tableListUrl,
        }).on("loaded.rs.jquery.bootgrid", function (e) {
            alert('Loaded');
        });
    }).on("click.rs.jquery.bootgrid", function (e, columns, row) {

});
},

self.RefreshTable = function () {
    self.gridObject.bootgrid("reload");
},

}

然后我可以使用:

初始化我的表格
<script type="text/javascript">
    $(function() {
        var dt = new dataTable();

        dt.InitilizeAjaxTable("sitesList", '@Url.Action("SitesList","Sites")');
    });
</script>

HTML:

<table id="sitesList" class="table table-hover table-striped">
    <thead>
        <tr>
            <th data-column-id="iSiteId" data-visible="false" data-identifier="true" data-type="numeric" data-sortable="false">Site Id</th>
            <th data-column-id="sSiteName" data-order="desc">Site Name</th>
            <th data-column-id="sNotes">Notes</th>
            <th data-column-id="sAddress">Address</th>
            <th data-column-id="sCity">City</th>
        </tr>
    </thead>
    <tbody></tbody>
</table>       

我知道我可以将rowSelectselection设置为true

我可以在按钮上绑定click事件,我需要知道的是如何在数据属性的表格开头附加按钮?

4 个答案:

答案 0 :(得分:3)

这个适用于我:

$("#grid-header").find('.actions.btn-group').append('<button class="btn btn-primary" type="button">Edit <span class="icon glyphicon glyphicon-pencil"></span></button>');

答案 1 :(得分:2)

这就是我实现我的按钮以便与bootgrid完美契合的方式:

$("#grid-header").find('.actionBar').prepend('
    <button id="btnAdd" class="btn btn-primary pull-left" type="button">
        <span class="icon glyphicon glyphicon-plus"></span>
        Add
    </button>
');

效果很好,在那里自定义按钮非常容易。

答案 2 :(得分:1)

好的,我扩展了jquery-bootgrid对象并创建了一个customDataTable对象。

您需要做的就是将以下代码复制/粘贴到JS文件中,并在链接jquery bootgrid JS文件后将其链接到您的网站。

  

注意:我添加了自定义requestHandlerresponseHandler,但如果您不需要,可以编辑或删除它 - 因为这是   我在申请中使用的是什么。

(function($) {

  $.fn.customDataTable = function(options) {
    var namespace = ".rs.jquery.bootgrid";
    var settings = $.extend({
      tableListUrl: null,
      buttons: [],
      refreshTables: [],
      updateParameters: '',
      canSearch: true,
      rowCount: [10, 25, 50, -1],
      ajax: true,
      css: {
        actions: 'actions btn-group',
        dropDownMenu: 'dropdown btn-group'
      },
      searchSettings: {
        characters: 2
      },
      rowSelect: true,
      templates: {
        header: "<div id=\"{{ctx.id}}\" class=\"{{css.header}}\"><div class=\"row\"><div class='col-md-12 bootgridMessage'></div><div class=\"col-sm-12 actionBar\"><p class=\"{{css.search}}\"></p><p class=\"{{css.actions}}\"></p></div></div></div>"
      }

    }, options);

    if (!settings.canSearch) {
      settings.templates.header = "<div id=\"{{ctx.id}}\" class=\"{{css.header}}\"><div class=\"row\"><div class='col-md-12 bootgridMessage'></div><div class=\"col-sm-12 actionBar\"><p class=\"{{css.actions}}\"></p></div></div></div>";
    }



    var createButtons = function() {
      var buttons = settings.buttons;
      var htmlButtons = [];

      $.each(buttons, function(name, props) {
        var css = "";
        if (!props.enabled) {
          css = " hidden";
        }
        var tempBtn = $("<button/>", {
          text: props.Text, //set text 1 to 10
          id: "btn_" + props.Text,
          "class": props.css + " pull-left" + css,
          click: props.click
        }).attr({
          "style": "margin-right: 5px;"
        });

        htmlButtons.push(tempBtn);

      });
      return htmlButtons;
    };
    var buttons = createButtons();
    var parentDiv = $(this).parent().parent();
    var dt = $(this).bootgrid({
      css: settings.css,
      rowCount: settings.rowCount,
      selection: settings.rowSelect,
      rowSelect: settings.rowSelect,
      searchSettings: settings.searchSettings,
      converters: {
        datetime: {
          from: function(value) {
            return moment(value);
          },
          to: function(value) {
            var customDateTime = moment.utc(value);
            return customDateTime.format("DD/MM/YYYY HH:mm:ss");
          }
        },
        date: {
          from: function(value) {
            return moment.utc(value);
          },
          to: function(value) {
            var customDateTime = moment.utc(value);
            return customDateTime.format("DD/MM/YYYY");
          }
        }
      },
      requestHandler: function(request) {
        var model = {};

        model.Current = request.current;
        model.RowCount = request.rowCount;
        model.Search = request.searchPhrase;

        for (var key in request.sort) {
          model.SortBy = key;
          model.SortDirection = request.sort[key];
        }

        return JSON.stringify(model);
      },
      responseHandler: function(response) {
        return response;
      },
      ajaxSettings: {
        method: "POST",
        contentType: "application/json"
      },
      ajax: settings.ajax,
      url: settings.tableListUrl,
      templates: settings.templates
    }).on("selected" + namespace, function(e, row) {

    }).on("load" + namespace, function(e) {});

    for (var i = 0; i < buttons.length; i++) {
      parentDiv.find(".actionBar").prepend(buttons[i]);
    }
    return dt;
  };

}(jQuery));

然后我创建了这样的bootgrid表:

var assetsList = $("#grid-data").customDataTable({
  ajax: false, // set to true to load data using Ajax
  buttons: {
    dlt: {
      Text: "Delete",
      css: "btn btn-danger",
      enabled: true, // false to hide button
      click: function() {
        alert('Delete clicked')
        var selectedId = assetsList.bootgrid("getSelectedRows")[0];
        if (selectedId == undefined) {
          alert('No Item Selected');
          return;
        }
      }
    },
    update: {
      Text: "Update",
      css: "btn btn-primary",
      enabled: true,
      click: function() {
        alert('update clicked')

      }
    }
  }
});

您可以根据需要传递任意数量的按钮,也可以定义它们执行的功能。

对于Ajax表,只需传入正确的URL并将ajax设置为true:

var assetsList = $("#grid-data").customDataTable({
  tableListUrl: '/Controller/Action',
  ajax: true,

你可以在这里看到一个有效的例子:https://jsfiddle.net/mdawood1991/m5j722gz/

答案 3 :(得分:0)

加载表后使用jQuery prepend函数:

$('#sitesList tr').prepend(
     '<th>' +
         '<button type="button" testDate="' + yourData + '">' +
              'click me' +
          '</button>' +
     '</th>'
);

在表格顶部添加一个按钮。