在JQuery UI Widget中访问.selector

我正在使用ui小部件工厂制作一个插件。 使用基本的JQuery插件,我可以通过这样的操作来访问使用的选择器…

$.fn.pluginname = function(){ var thisWorks = this.selector; }; 

但是,当我使用小部件工厂时,通过’this.element’属性访问所选元素,’this.element.selector’与我的第一个示例中的工作方式不同。 任何人都有一个很好的方法吗? 我正在浏览GitHub上的widget工程源代码,但我还没有找到任何东西。

诀窍是,在widget工厂完成创建窗口小部件之后,它基本上只是一个普通的插件。 这意味着您可以进一步扩展它。

我们的想法是保存原始函数,将其替换为自定义函数并使其通过选择器。 此代码可以在窗口小部件工厂之后和第一次使用对象之前的任何位置。 在调用$.widget()之后将它放在你的插件文件中。

此示例中的窗口小部件的名称是test

 // Save the original factory function in a variable var testFactory = $.fn.test; // Replace the function with our own implementation $.fn.test = function(obj){ // Add the selector property to the options $.extend(obj, { selector: this.selector }); // Run the original factory function with proper context and arguments return testFactory.apply(this,arguments); }; 

这可以确保this.selector作为命名选项传递。 现在,您可以通过引用this.options.selector在工厂内的任何位置访问它。

另外,我们不需要破解任何jQuery UI代码。

只是我的几分钱……这里是基于DarthJDG答案的JSFiddle示例…可能有人会需要它。

 $(function () { $.widget("test.testwidget", { _create: function () { this.element.text('Selector: ' + this.options.selector) }, }); }(jQuery)); // Save the original factory function in a variable var testFactory = $.fn.testwidget; // Replace the function with our own implementation $.fn.testwidget = function(obj){ // Add the selector property to the options $.extend(obj, { selector: this.selector }); // Run the original factory function with proper context and arguments return testFactory.apply(this,arguments); }; $(document).ready(function() { $('#test').testwidget({}); $('.test').testwidget({}); }); 

也可以简单地使用

 this.selector = '#'+this.element.attr('id'); 

通常在_create方法中。 当然,这要求您的窗口小部件的每个实例都具有通常应该使用的唯一ID。