【问题标题】:jQuery plug-in with additional methods带有附加方法的 jQuery 插件
【发布时间】:2009-09-08 13:28:11
【问题描述】:

我有一个 jQuery 插件,可以对一些 UL 进行操作,添加和删除类等。

在页面的生命周期中,我需要在代码中添加/删除一些类,并且由于我的插件需要在发生这种情况时执行一些额外的操作,所以我想出了以下内容:

// This is the initialiser method...
$.fn.objectBuilder = function (options) {...};
// These are the two new methods I need.
$.fn.objectBuilder.setSelected(element) {...};
$.fn.objectBuilder.removeSelected() {...};

然后我想这样称呼他们:

$("#ob1").objectbuilder.removeSelected();

有什么想法吗?

谢谢, 基隆

编辑

我想我要问的是,向 jQuery 插件添加其他方法的最佳方法是什么,它可以访问根对象,在这种情况下是调用方法时的 #obj。

【问题讨论】:

    标签: jquery jquery-plugins


    【解决方案1】:

    我对此的解决方案一直是事件。我在每个对象上设置了命名空间事件,以便以后可以触发它们:

    $.fn.testPlugin = function() {
      return this.each(function() {
        $(this).bind('testPlugin.event1', function() {
           blah, blah, blah;
        });
      });
    };
    

    后来……

    $('#obj1').trigger('testPlugin.event1');
    

    jQuery UI 使用另一种更复杂的解决方案。你可以在这里查看:http://jqueryui.com/docs/Developer_Guide

    【讨论】:

    • 开发者指南正是我想要的,谢谢!
    猜你喜欢
    • 2011-06-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-11-09
    • 1970-01-01
    • 2011-05-16
    • 1970-01-01
    相关资源
    最近更新 更多