(function($){
$.fn.slideshow = function(){
function init(obj){
setInterval("startShow()", 3000);
}
function startShow(){
alert('h');
}
return this.each(function(){
init(this);
});
}
})(jQuery);
我收到错误
startShow is not defined
答案 0 :(得分:7)
更改
setInterval("startShow()", 3000);
要
setInterval(startShow, 3000);
将字符串传递给setInterval()时,内部代码在当前范围之外执行。无论如何,通过该功能更合适。如果您将括号括起来,函数可以像任何其他变量一样传递。
如果您需要传递变量,可以使用类似于the one Guffa provided的解决方案:
setInterval(function () { startShow(myVar); }, 3000);
这将创建一个匿名函数作为 setInterval()的第一个参数传递,并且在该匿名函数中,您可以访问范围链中的变量和函数。
答案 1 :(得分:6)
startShow
函数是作用域的本地函数,因此当setInterval
方法计算全局作用域中的字符串时,它将找不到该函数。
使用匿名函数而不是字符串:
setInterval(function(){ startShow(); }, 3000);
由于匿名函数使用本地声明的函数,因此创建了一个闭包,以便函数仍然可以访问它。
答案 2 :(得分:0)
function startShow()
{
alert('h');
}
(function($){
$.fn.slideshow = function(){
function init(obj){
setInterval("startShow()", 3000);
}
return this.each(function(){
init(this);
});
}
})(jQuery);
答案 3 :(得分:0)
将字符串传递给setInterval / setTimeout使其在后台运行eval()。函数范围在此eval中丢失,需要全局引用。避免在setInterval / setTimeout中使用字符串,它永远不需要并导致变形。
(function($){
$.fn.slideshow = function(){
var init = function(obj){
setInterval(startShow, 3000);
}
var startShow = function(){
alert('h');
}
return this.each(function(){
init(this);
});
}
})(jQuery);
答案 4 :(得分:0)
您设置超时以查看基本范围,您需要在
中创建一个匿名函数尝试以下方法:
(function($){
$.fn.slideshow = function(){
function init(obj){
setInterval(function(){
startShow();
}, 3000);
}
function startShow(){
//Deprecated
}
return this.each(function(){
init(this);
});
}
})(jQuery);
或者您可以创建一个对象来保存您的方法:
(function($){
$.fn.slideshow = function(){
var Functions = {
startShow : function(obj)
{
alert('Starting Show')
}
}
function init(obj){
setInterval(function(){
Functions.startShow(obj)
}, 3000);
}
return this.each(function(){
init(this);
});
}
})(jQuery);
答案 5 :(得分:0)
这与您的问题没有直接关系,但如果您查看此页面,您会发现创建插件方法时的最佳做法:
http://docs.jquery.com/Plugins/Authoring
这只是一个例子:
(function( $ ){
var methods = {
init : function( options ) {
setInterval(startShow(), 3000);
},
startShow : function( ) {
alert('h');
}
};
$.fn.slideshow = function( method ) {
// Method calling logic
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 on jQuery.tooltip' );
}
};
})( jQuery );