Javascript setTimeout立即运行
我的页面上有一些元素,我想通过JQuery扩展函数调用它们上面的函数。我有此功能声明:Javascript setTimeout立即运行,javascript,jquery,web,Javascript,Jquery,Web,我的页面上有一些元素,我想通过JQuery扩展函数调用它们上面的函数。我有此功能声明: (function ($) { $.fn.enable = function (delay) { console.log(delay); //logs 3000 setTimeout(function (elem) { console.log(elem); elem.css("opa
(function ($) {
$.fn.enable = function (delay) {
console.log(delay); //logs 3000
setTimeout(function (elem) {
console.log(elem);
elem.css("opacity", "1");
}(this), delay);
return this;
};
})(jQuery);
如您所知,它在JQuery对象上声明了一个enable
函数。现在,当我把这样的事情称为:
$("#start").enable(3000);
函数enable
运行,但是函数(elem).
中的代码立即运行,而不是在一段时间后运行
如何以及为什么???这是因为您正在调用函数“function(elem)”,而不是将其作为参数提供。试试这个
(function ($) {
$.fn.enable = function (delay) {
console.log(delay); //logs 3000
var elem = this;
setTimeout(function () {
console.log(elem);
elem.css("opacity", "1");
}, delay); //you should not call a function here
return this;
};
})(jQuery);
这是因为您正在调用函数“function(elem)”,而不是将其作为参数提供。试试这个
(function ($) {
$.fn.enable = function (delay) {
console.log(delay); //logs 3000
var elem = this;
setTimeout(function () {
console.log(elem);
elem.css("opacity", "1");
}, delay); //you should not call a function here
return this;
};
})(jQuery);
这是因为您正在调用函数“function(elem)”,而不是将其作为参数提供。试试这个
(function ($) {
$.fn.enable = function (delay) {
console.log(delay); //logs 3000
var elem = this;
setTimeout(function () {
console.log(elem);
elem.css("opacity", "1");
}, delay); //you should not call a function here
return this;
};
})(jQuery);
这是因为您正在调用函数“function(elem)”,而不是将其作为参数提供。试试这个
(function ($) {
$.fn.enable = function (delay) {
console.log(delay); //logs 3000
var elem = this;
setTimeout(function () {
console.log(elem);
elem.css("opacity", "1");
}, delay); //you should not call a function here
return this;
};
})(jQuery);
如果以
(this)
结束匿名函数,则传递的是它的返回值,而不是函数。如果以(this)
结束匿名函数,则传递的是它的返回值,而不是函数。如果以(this)
结束匿名函数,则传递的是它的返回值,不是函数。如果以(this)
结束匿名函数,则传递的是它的返回值,而不是函数。