如何将标准API功能添加到jQuery插件中

How to add standard API functionality to jQuery plugin

本文关键字:jQuery 插件 添加 功能 标准 API      更新时间:2023-09-26

在我创建的jQuery插件中,要从插件外部访问其方法,我必须执行类似的操作

$("#testItem").data('pluginName').foo_public_method()

然而,我看到其他插件提供了类似的API

$('#testItem').pluginName('foo_public_method')

如何启用此类功能?

jsFiddle

您需要询问传递给插件实例的参数,并检查插件是否已经在元素上实例化。

从您的示例来看,插件实例存储在元素的data属性中,因此检查起来应该很简单。然后,您可以使用arguments关键字来访问已传入的任何内容。

在下面的代码中,我将this作为插件调用的单个元素

var instance = $(this).data('pluginname');
var args = $.makeArray(arguments);
if (!instance) {
    // create the plugin on the element using args as an object
}
else {
    // plugin already exists
    if (typeof args[0] == "string") {
        // arg0 = property
        // arg1 = value
    }
    else {
        // logic for passing in arguments as an object
    }
}