Jquery 调用函数中的函数以初始化
上面返回“this.each不是函数”Jquery 调用函数中的函数以初始化,jquery,function,variables,plugins,init,Jquery,Function,Variables,Plugins,Init,上面返回“this.each不是函数” 任何帮助都将不胜感激!非常感谢 为了使方法调用不必传入对象,我通常使用以下格式: return this.each(function(){ var $this = $(this), data = $this.data('pluginName'); if ( ! data ) { $(this).data('pluginName', { target : $this
任何帮助都将不胜感激!非常感谢 为了使方法调用不必传入对象,我通常使用以下格式:
return this.each(function(){
var $this = $(this),
data = $this.data('pluginName');
if ( ! data ) {
$(this).data('pluginName', {
target : $this
});
}
}).bind(this);
您可以像这样访问它:
(function($) {
function doSomething() {
// Only callable in this plugin's context (I think)
}
var methods = {
init: function (options) {
// Do whatever for init!
doSomething();
},
anotherMethod: function (options) {
// Some other method
doSomething();
}
};
$.fn.pollServer = function(method) {
var args = arguments;
var argss = Array.prototype.slice.call(args, 1);
return this.each(function () {
$this = $(this);
if (methods[method]) {
methods[method].apply($this, argss);
}
else if (typeof method === "object" || !method) {
methods.init.apply($this, args);
}
else {
$.error("Method " + method + " does not exist on jQuery.pollServer");
}
});
};
})(jQuery);
函数中的所有内容都返回this.each()确定要调用的方法,并将“this”变量设置为所选的jQuery元素。它还将其他参数传递给方法
希望这有帮助 这太棒了!!非常感谢。我会处理这个。我已经写了一个不同的模式,但你的似乎更符合逻辑。一旦我实现了您的解决方案,我将再次发表评论,并让您知道它是如何工作的!非常感谢!没问题!我在jQuery网站的某个地方找到了类似的东西,但对它进行了一些修改以满足我的需要。它对我有用,所以我希望它能帮助你!如果你需要更多类似的指导,请告诉我好的,我不想开始把我的代码弄得一团糟。init函数工作得很好,谢谢!所以我有两个新问题,我想我是金。。。首先如何从“init”中调用函数?记住它在“methods”变量中。同样,我如何使用“methods”变量中的函数从“pollServer()”中调用函数?任何你能给出的关于参数传递的例子都是非常特别的!你已经帮了我很多!非常感谢。为了更好地参考,我添加了下面的代码。它不是100%,我有不同的文件与其他功能部件一起保存。一旦我能够理解这一点,我将能够添加这些函数:)
(function($) {
function doSomething() {
// Only callable in this plugin's context (I think)
}
var methods = {
init: function (options) {
// Do whatever for init!
doSomething();
},
anotherMethod: function (options) {
// Some other method
doSomething();
}
};
$.fn.pollServer = function(method) {
var args = arguments;
var argss = Array.prototype.slice.call(args, 1);
return this.each(function () {
$this = $(this);
if (methods[method]) {
methods[method].apply($this, argss);
}
else if (typeof method === "object" || !method) {
methods.init.apply($this, args);
}
else {
$.error("Method " + method + " does not exist on jQuery.pollServer");
}
});
};
})(jQuery);
$("#div").pollServer({});
$("#div").pollServer("init", {}); // Same as above line
$("#div").pollServer("anotherMethod", {});