我已经很长时间没有使用 Javascript 了,今天又重新学习了它。一直让我着迷的一件事是this
关键词。我知道在 jQuery 事件处理程序中,例如单击事件,this
指的是触发事件的元素。怎么this
传递给我作为回调提供的函数,即使我的函数没有参数?
给出以下代码:
$("tr.SummaryTbRow").data("Animating", false);
$("tr.SummaryTbAltRow").data("Animating", false);
$("tr.SummaryTbRow").click(function () {
if ($(this).data("Animating") == false) {
if ($(this).next(".Graph").css("display") == "none") {
$(this).data("Animating", true);
//Part I am questioning.
setTimeout(function () {
$(this).data("Animating", false);
}(this), 550);
$(this).next(".Graph").slideRow('down', 500);
}
else {
$(this).data("Animating", true);
$(this).next(".Graph").slideRow('up', 500);
}
}
});
我想弄清楚如何用类传递元素表行SummaryTbRow
到我的 setTimeout 回调函数。 jQuery 是否通过this
与我对匿名回调函数所做的类似吗?我的吗this
函数内部引用this
我进去了?
我知道我可以这样做:
setTimeout(function (element) {
$(element).data("Animating", false);
}(this), 550);
但我想弄清楚 jQuery 是如何能够通过this
到我的回调函数,即使我的函数接受 0 个参数。
为了回答你最后一个问题,你可以将你选择的接收者传递给 javascript 中的函数,例如call https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Function/call :
someFunction.call(someObject);
Inside someFunction
, this
将someObject
.
就你而言,你似乎想要的是
setTimeout(function (element) {
$(element).data("Animating", false);
}, 550, this); // this will be passed as element to the callback
or (更兼容 https://developer.mozilla.org/en-US/docs/DOM/window.setTimeout)
var _this = this;
setTimeout(function () {
$(_this).data("Animating", false);
}, 550);
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)