【问题标题】:How to shorten these repeated jQuery plugin parameters?如何缩短这些重复的jQuery插件参数?
【发布时间】:2010-08-28 12:22:39
【问题描述】:

我正在使用 DataTables jQuery 插件。我希望我的表格工作的方式意味着我将很多参数传递给插件以关闭一些东西:

$('table.data').dataTable( {
    'aoColumns': [
        null,
        { 'bSortable': false },
        { 'bSortable': false },
        { 'asSorting': ['desc','asc'], 'sType': 'blanks' },
        { 'asSorting': ['desc','asc'] }
    ],
    'bPaginate': false,
    'bAutoWidth': false,
    'bInfo': false,
    'bProcessing': true,
    'asStripClasses': [],
    'sDom': 'rt'
} );

在不同的页面中,aoColumns 参数会根据表格变化,但其他参数保持不变。什么是最好的方法来避免我一遍又一遍地重复代码(如果我以后改变对参数的想法,它会更容易)?

我尝试使用{'bPaginate': false ...} 存储参数,但这会创建一个子对象。也许有一种方法可以“合并”内联对象或其他东西?

【问题讨论】:

    标签: jquery parameters datatable


    【解决方案1】:

    如果您经常这样做,您可以添加自己的jQuery plugin

    jQuery.fn.myDataTable = function(aoColumns) {
        return this.dataTable({
            'aoColumns': aoColumns,
            'bPaginate': false,
            'bAutoWidth': false,
            'bInfo': false,
            'bProcessing': true,
            'asStripClasses': [],
            'sDom': 'rt'
        });
    };
    

    【讨论】:

      【解决方案2】:

      将重复使用的放在一个变量中:

      var reused = {
         'bPaginate': false,'bAutoWidth': false,
          'bInfo': false,
          'bProcessing': true,
          'asStripClasses': [],
          'sDom': 'rt'
      }
      

      然后使用$.extend合并唯一数据:

      $('table.data').dataTable( 
          $.extend(
              {},  // Empty target that is extended and passed to dataTable 
              reused, // Extend with the stored reused data
              {'aoColumns': [ // Extend with an object containing the unique propertie(s)
                     null,
                     { 'bSortable': false },
                     { 'bSortable': false },
                     { 'asSorting': ['desc','asc'], 'sType': 'blanks' },
                     { 'asSorting': ['desc','asc'] }
                  ]
              }
          )
      );
      

      编辑:我的一个关闭者是},而不是)。固定。

      请注意,如果您想覆盖您的reused 属性之一,您可以在$.extend() 变量之后的任意位置添加另一个对象。这不会影响存储在reused 中的项目。

      $.extend(
              {},  
              reused,
              {'bInfo': true}, // override one of the properties in "reused"
              {aoColumns:// ...etc
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2018-09-18
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2010-10-23
        相关资源
        最近更新 更多