gpt4 book ai didi

javascript - jQuery 实用程序样板

转载 作者:行者123 更新时间:2023-12-03 11:17:23 26 4
gpt4 key购买 nike

我正在尝试从 jQuery Boilerplate 创建一个 jQuery 插件。我还想创建另一个与此插件分开的实用程序类型插件。我一直在谷歌上搜索不同的方法来创建这样的东西。我遇到过很多不同的类型,我不确定从哪里开始,所以我转向 StackOverflow,希望你能帮助指导我。

我的目标是调用我的插件(实用方法/函数)并向其传递一些选项和数据,并让它返回一些数据,无论是对象、字符串还是数组,具体取决于调用的函数。

我想做这样的事情:

<script>
var options = {option1: 'value1', option2: 'value2'};
var output = $.myplugin('methodName', options);
</script>

但是,我想尊重插件命名空间、正确的 jQuery 礼仪等。

最佳答案

jQuery 有两种类型的实用程序“插件”(由于缺乏更好的术语)。第一个是向实际的 jQuery 对象添加一个方法,也是最容易实现的,第二个是添加到期望发生特定事情的 jQuery 对象实例(链接、迭代、上下文管理、事件等)。

实用函数

这是一个简单的方法,因为您不是操作 jQuery 对象,而是只是扩展 jQuery,就像它是任何普通的 JavaScript 对象一样。只需将一个函数分配给 jQuery(或简称为 $)即可达到目的。

jQuery.myNewRadUtility = function myNewRadUtility(input, options) {
// Do something with input and options
return someValue; // return what you want
};

// Use it in your other code like so:
$.myNewRadUtility(input, options); // Or what ever you plan on doing

正如您所看到的,它只是一个与其他函数一样的函数,只不过您将它分配给 jQuery 对象上的属性。

为了使事情更加通用/混合的方法,您可以分离函数并像通用一样编写它,然后将其附加到 jQuery 特定文件中的 jQuery 或以实用的方式。

function myNewRadUtility() {
// Do one and only one amazing thing here.
}

// If we have jQuery then lets use it.
if (jQuery) {
jQuery.myNewRadUtility = myNewRadUtility;
}

// Or if you need to massage the input / output to conform to jQuery then
if (jQuery) {
jQuery.myNewRadUtility = function() {
// Massage the input here
var result = myNewRadUtility();
// Massage the output here
return result;
};
}

jQuery 插件

这有点先进,因为您必须考虑 jQuery 对象期望如何使用。首先,像上面那样使用 jQuery 的 fn 属性附加到原型(prototype)。然后您必须管理该实用程序需要使用的 jQuery 对象。这意味着迭代它们。最后,您需要根据您创建的实用程序的目的返回相同或新的实例(通常不仅仅是返回 this)。

jQuery.fn.myNewRadUtility = function myNewRadUtility() {
return $(this).each(function() {
// Do something with $(this)
});
};

// Use it in your other code like so:
$('p').myNewRadUtility();

显然,还有很多事情要做,而且您可以做很多事情。但这是品尝的最低限度。

关于javascript - jQuery 实用程序样板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27281865/

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