6

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

Bootstrap select destroy 从 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();
}
4

2 回答 2

2

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

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

然后

$smth.selectpicker("customRemove");
于 2015-09-10T16:32:03.233 回答
1

您可以使用 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 选择的原型并修改其行为。

于 2015-03-19T11:10:35.810 回答