【问题标题】:Extend bootstrap select plugin扩展引导选择插件
【发布时间】:2015-02-04 17:13:00
【问题描述】:

在我之前的问题中,我谈到了 bootstrap 选择插件,其中destroy 方法正在做一些我不想要的事情。我手动编辑插件,但这不是一个好习惯。

Bootstrap select destroy removes the original select from DOM

我想使用自定义方法扩展插件,以便它可以完全按照我的意愿行事。

我使用以下方法扩展插件:

$.extend(true, $.fn.selectpicker.prototype, {
    customRemove: function () {
        this.$newElement.remove();
        this.$element.show();
    }
});

这位于引导选择脚本文件下的另一个js文件中。

如何调用这个新方法?我尝试了以下但没有成功:

$('select#begin' + _week + _day).selectpicker("customRemove");

$('select#begin' + _week + _day).selectpicker().customRemove();

我错过了什么吗?

bootstrap select插件中destroy函数的原方法:

remove: function () {
  this.$newElement.remove();
  this.$element.show();
}

【问题讨论】:

  • selectpicker() 是否返回 this?如果不是,那么您不能链接该方法。
  • 我在插件中看到return this; 所以是的
  • 试试 selectpicker.prototype.customRemove();
  • @Dave 谢谢我现在可以调用我的方法,但变量未定义。如何获取位于Selectpicker 类中的this.$newElementthis.$element 的值?
  • 检查.. customRemove: function (ele) { ele.$newElement.remove(); ele.$element.show(); }

标签: jquery twitter-bootstrap bootstrap-select


【解决方案1】:

我认为,您在其他问题中的正确答案是:
https://stackoverflow.com/a/31852632/4928642

jQuery.fn.selectpicker.Constructor.prototype.customRemove = function () {
  this.$newElement.remove();
  this.$element.show();
};

然后

$smth.selectpicker("customRemove");

【讨论】:

    【解决方案2】:

    您可以使用 mixin 闭包将函数代理为您自己的函数,例如:

    (function()
    {
      // grab a reference to the existing remove function
      var _remove = $.fn.selectpicker.prototype.remove;
    
      // anything declared in here is private to this closure
      // so you could declare helper functions or variables
      // ...
    
      // extend the prototype with your mixin
      $.extend(true, $.fn.selectpicker.prototype, 
      {
        // this will replace the original $.fn.selectpicker.prototype.remove function
        remove: function () 
        {
          // call whatever code you want here
          // ...
          // ... like grabbing the DOM element
          // ...
          // then call the original remove function
          _remove.apply(this, arguments);
    
          // then call whatever you want here, like re-adding the DOM element
        }
      });
    }());
    

    注意:这将覆盖所有 Bootstrap 选择的原型并修改其行为。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-11-25
      • 2015-09-03
      • 2012-12-08
      • 1970-01-01
      • 1970-01-01
      • 2011-08-14
      • 1970-01-01
      相关资源
      最近更新 更多