【问题标题】:Accessing public/private methods of a jQuery widget from within an .each() method inside that widget从该小部件内的 .each() 方法中访问 jQuery 小部件的公共/私有方法
【发布时间】:2016-11-16 16:57:07
【问题描述】:

我正在尝试在 jQuery 中扩展 Tabs 小部件,以便它在创建新选项卡(由用户触发)或页面加载(对于任何预先存在的选项卡)时自动将某些 html 添加到选项卡。通过使用常规选项卡小部件和一堆自定义 JavaScript 函数,我能够让所有这些在小部件外部工作。但是,为了使其更加模块化,我希望这些函数成为我的扩展小部件的成员函数。

小部件:

$.widget( "custom.extendedTabs", $.ui.tabs, {
    ,_addOptions: function($el) {
        //add a "close" button and an "options" button on each tab on mouseover
    }   
    ,_create: function() {
        this.element.find("li").each(function(i,el){
            this._addOptions($(this));
        });
        return this._super();
    }
    ,addTab: function() {
        //handle tab creation
        ........
        this._addOptions(<newlyCreatedliElement>);
    }
});

实例化:

$(".tabs").each(function(){
    $(this).extendedTabs();
});

示例:

<div id="tabs1" class="tabs">
  <ul>
    <li><a href="#tabs-1">Nunc tincidunt</a></li>
    <li><a href="#tabs-2">Proin dolor</a></li>
  </ul>
  <div id="tabs-1">
    <p>Proin elit arcu, rutrum commodo, vehicula tempus, commodo a, risus.</p>
  </div>
  <div id="tabs-2">
    <p>Morbi tincidunt, dui sit amet facilisis feugiat, odio metus.</p>
  </div>
</div>

<div id="tabs2" class="tabs">
  <ul>
    <li><a href="#tabs-3">Nunc tincidunt</a></li>
  </ul>
  <div id="tabs-3">
    <p>Proin elit arcu, rutrum commodo, vehicula tempus, commodo a, risus.</p>
  </div>
</div>

问题:

根据测试,我直接从_create() 调用this._addOptions() 没有问题。但是,从_create() 内部的.each() 调用它时,我没有同样的成功。尝试这样做时,我收到 this.addOptions is not a function 作为错误。

我知道.each() 内部的this 代表迭代的实例元素本身,而不是调用它的父小部件。但我认为可能有一些方法可以引用名为 .each() 的对象。

更新:

我成功地将.each() 替换为以下内容:

for (var el in this.element.find("li").toArray()) {
    this._addOptions($(this.element.find("li").toArray()[el]));
}

然而,这感觉很笨拙,所以我仍然希望有人能提供一些更简洁的方法。

【问题讨论】:

    标签: jquery scope widget each


    【解决方案1】:

    我考虑过另一种解决方案——保留 jQuery .each():

    ,_create: function() {
        var self=this;
        this.element.find("li").each(function(i,el){
            self._addOptions($(this));
        });
        return this._super();
    }
    

    【讨论】:

      猜你喜欢
      • 2011-02-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-02-11
      • 1970-01-01
      • 1970-01-01
      • 2016-09-09
      • 1970-01-01
      相关资源
      最近更新 更多