好吧,我对这句话说“$ .Recup ...”感到困惑。我不知道为什么它的名字与插件名称相同,以及它的用途。
(function ($) {
$.fn.Recup = function () {
var parametros = {
};
var tsic = true;
$.Recup = function (opciones) {
var Metodos = {
};
return Metodos;
};
$.Recup.anterior = function () {
};
$.Recup.siguiente = function () {
}
})(jQuery);
我正在引用这段代码,$.Recup
到底做了什么?如果有人给我一个例子,那将是完美的
$.Recup = function (opciones) {
var Metodos = {
};
return Metodos;
};
答案 0 :(得分:2)
在这种情况下,它似乎是一个值得怀疑的插件设计 - ,尤其是在$.Recup
首次调用之前未分配$.fn.Recup
。
但是,如果“适当和/或写得好”是另一个需要(预期)使用背景的问题。对于它的价值,我会拒绝这些代码,因为它闻起来有误解的设计和广泛的副作用。
无论如何,分配函数的方式决定了如何调用该方法。
// let $ be jQuery, then:
$.fn.foo = function () { console.log("foo") }
$.bar = function () { console.log("bar") }
$.foo() // TypeError: $.foo is not a function
$.bar() // -> "bar"
$("sel").foo() // -> "foo"
$("sel").bar() // TypeError: $(..).bar is not a function
也就是说,$.fn.foo
与.each()
类似 - 它根据当前选定的元素(由this
表示)执行某些操作。另一方面,$.bar
与jQuery.each()
类似 - 它提供了一种迭代一般集合的方法,但与一组特定的(先前)选定元素无关。
一般情况下,插件只应 向$.fn
添加一个条目,但直接添加到$
可能对于公开实用程序很有用功能 - 绝对应该小心。
以下两种方法可以解决错误泄露数据的问题:
$.fn.Recup = function () {
var parametros = ..
var tsic = true;
// Most trivial change; then use recup in this scope
// (or child scopes) only. There is no $.Recup - yay!
var recup = function (opciones) {
};
// ..
}
或者,只是作为本地方法公开:
$.fn.Recup = function () {
var parametros = ..
var tsic = true;
function anterior () {
}
function siguiente () {
}
// Just use simple functions in scope
}
答案 1 :(得分:0)
这是一个jQuery插件。
jQuery.fn
是jQuery原型的别名。因此,这一行允许您在jQuery实例上调用Recup
函数:
$('#myid').Recup();