gpt4 book ai didi

javascript - 插件方法 - 这里有什么魔力?

转载 作者:行者123 更新时间:2023-12-02 20:13:53 24 4
gpt4 key购买 nike

我挣扎着,终于得到了[ this ] 上类。现在,我想将其分解,如下所示,但它不起作用......这里有一些我不明白的巫毒吗?

<!DOCTYPE html>
<html>
<head>
<!-- jQuery -->
<script type="text/javascript" src="http://goo.gl/XQPhA"></script>
<script type="text/javascript">
(function($) {
$.test = function(options) {
options = $.extend({}, $.test.settings, options);

this.whiten = function() {
$(this).css('background-color', options.bg);
};
};
$.test.settings = { bg: 'white' };

$.fn.test = function(options) {
return this.each(function(index, el) {
$.test(options);
});
};
})(jQuery);

$(document).ready(function() {
$('ul').test().css('background-color', 'wheat');
$('#go').click(function() {
$('ul').whiten();
});
});
</script>
</head>

<body>
<button id="go">whiten</button>
<ul id="list1">
<li>Aloe</li>
<li>Bergamot</li>
<li>Calendula</li>
<li>Damiana</li>
<li>Elderflower</li>
<li>Feverfew</li>
</ul>
<ul id="list2">
<li>Ginger</li>
<li>Hops</li>
<li>Iris</li>
<li>Juniper</li>
<li>Kavakava</li>
<li>Lavender</li>
<li>Marjoram</li>
<li>Nutmeg</li>
<li>Oregano</li>
<li>Pennroyal</li>
</ul>
</body>
</html>

与之前的代码相比,在 each() 循环内部,我现在调用 $.test(options) 而不是 $.fn.test (选项) - 那么为什么一个有效而另一个无效(实际上,第一个为什么/如何开始工作)?

最佳答案

我会重组您的插件以遵循 plugin authoring guide 中概述的指南,最值得注意的是使用 .data() 存储小部件设置的数据,并使用 .test("method") 对插件进行方法调用:

(function($) {
/* Default plugin settings: */
var settings = {
bg: 'white'
};

/* Method definitions: */
var methods = {
init: function(options) {
options = $.extend({}, options, settings);
return this.each(function () {
$(this).data("test", options);
});
},
whiten: function() {
var options = this.data("test");
this.css('background-color', options.bg);
}
};

/* Plugin definition and method calling logic: */
$.fn.test = function(method) {
if (methods[method]) {
return methods[method].apply(this, Array.prototype.slice.call(arguments, 1));
} else if (typeof method === 'object' || !method) {
return methods.init.apply(this, arguments);
} else {
$.error('Method ' + method + ' does not exist');
}
}
})(jQuery);

用法:$("elem").test(), $("elem").test("whiten")

这是一个工作示例:http://jsfiddle.net/z4R3X/

插件创作指南的另一个资源是 jQueryUI 源代码(以 autocomplete widget 为例)。这些小部件是如何创建可重用、可读的 jQuery 插件的很好示例。

关于javascript - 插件方法 - 这里有什么魔力?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6605205/

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