我想要显示消息,然后使用setTimeout函数隐藏它们。所以我希望传递给setTimeout函数的函数接受一个参数,隐藏消息,这样我就可以使用一个泛型回调函数。我尝试了下面的代码,但是在回调执行时label参数是未定义的。
var label = $('.js-a-label');
label.html('the message!');
setTimeout(hideMessage(label), 5000);
function hideMessage(label) {
label.html('');
}发布于 2015-06-11 23:32:23
在该代码中,您可以只使用label,因为您的函数关闭了它:
var label = $('.js-a-label');
label.html('the message!');
setTimeout(hideMessage, 5000);
function hideMessage() {
label.html('');
}在一般情况下,当您调用的函数没有关闭您希望它使用的信息时,您有几个选择:
var label = $('.js-a-label');label.html(‘消息!’);setTimeout(function() { hideMessage(label);},5000);
Function#bind (ES5+)var label = $('.js-a-label');label.html(‘消息!’);setTimeout(hideMessage.bind(null,label),5000);
Function#bind返回一个新函数,当调用该函数时,将使用特定的this值调用原始函数(我们不需要该值,所以我只使用了上面的null )以及您给出的任何参数null $.proxy,它的作用与Function#bind大致相同:
var label = $('.js-a-label');label.html(‘消息!’);setTimeout($.proxy(hideMessage,null,label),5000);
https://stackoverflow.com/questions/30785147
复制相似问题