gpt4 book ai didi

jquery - 如何扩展 jQuery 插件?

转载 作者:行者123 更新时间:2023-11-30 23:45:10 27 4
gpt4 key购买 nike

我想创建一个 jQuery 插件来包装图表组件。它将具有 addLineSerie 或 addBarsSerie 等功能。然后我想创建其他插件来扩展这个插件以添加新功能或覆盖所需的内容,但仍然能够调用原始插件功能。

我从下面的方法开始。它有点有效,但是,正如我后来意识到的那样,我无法调用原始的“父”实现(如果我创建 myB 的实例,我无法调用 myA.goA2)。

(function($){
$.fn.myA = function(settings) {
this.goA = function() {alert("goA: "+settings);};
this.goA2 = function() {alert("goA2: "+settings);};
return this;
};
})(jQuery);

(function($){
$.fn.myB = function(settings) {
this.myA(settings);
this.goA2 = function() {alert("goA2B: "+settings);};
this.goB = function() {alert("goB: "+settings);};
return this;
};
})(jQuery);

所以我有两个问题:

  1. 这种方法正确吗?还是我应该采用不同的方式?
  2. 如何使“父级”和“子级”成​​为同一实例并调用“父级”的实现?

谢谢。

最佳答案

这似乎是正确的,但是要实现跨插件行为,你不能这样做:

(function($) {
$.fn.myA = function(settings) {
this.goA = function() {
alert("goA: " + settings);
};
this.goA2 = function() {
alert("goA2: " + settings);
};
return this;
};
})(jQuery);

(function($) {
$.fn.myB = function(settings) {
this.myA = $.fn.myA(settings);
this.goA2fromA = function() {
this.myA.goA2();
};
this.goA2 = function() {
alert("goA2B: " + settings);
};
this.goB = function() {
alert("goB: " + settings);
};
return this;
};
})(jQuery);

$(document).ready(function() {
var a = $('#one').myA({});
var b = $('#one').myB({});
a.goA2();
b.goA2fromA();
});

编辑:修复了对 myA 的调用并添加了将进行的调用。查看工作 fiddle :

http://jsfiddle.net/PqQgs/4/

关于jquery - 如何扩展 jQuery 插件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6051308/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com