【发布时间】:2013-03-08 05:09:05
【问题描述】:
我将以一种很好的方式包装我的一些函数,为此我想使用 jQuery 方法。就像 jQuery 有很多方法一样
$.parseJson()
$.ajax()
$("div").text("hey my testing");
这两种方法都存在于同一个 jQuery 文件中。但是在阅读如何制作 jquery 插件时,它指定您不需要在同一个插件中创建多个函数。而是传递一个包含方法名称的参数作为字符串。
那么,下面的 sn-p 是正确的还是我需要对其进行一些更正。
<script type="text/javascript">
(function ($) {
$.fn.testMethod1 = function () {
return $(this).each(function () { });
};
$.fn.testMethod2 = function () {
return $(this).each(function () { });
};
$.test = function () {
return "testresult"
};
})(jQuery);
$("div1").testMethod1();
$("div2").testMethod2();
$.test();
//Is that needed to be replace in a different way like
$("div1").myPlugin("testMethod1");
$("div1").myPlugin("testMethod2");
$("div1").myPlugin("test");
</script>
【问题讨论】:
-
this已经是一个 jQuery 对象。你不需要重新包装它。 -
好的,接受。但是同一个插件中的多个方法是正确的吗?
-
Twitter Bootstrap 就是这样做的,我认为如果所有插件都遵循相同的语法会更直观。
-
@Blender - 第一种方式还是第二种方式?
-
@Blender 但它就像我们通过他们的名字来调用插件一样。例如$("div").myPlugin("externalPlugin1",data) 和 $("div").myPlugin("externalPlugin2")
标签: javascript jquery jquery-plugins plugins