我有一个我不能理解的问题:
var Copyright =
{
onLoad: function () {
this.initCopyrightMoving();
},
initCopyrightMoving: function () {
$(".sidebar_toggle").click(function () {
var copyright = document.getElementById("copyright-text");
if (copyright.className == "copyright-menu-open") {
this.decrease(280, 80, 10, copyright);
}
else
copyright.className = "copyright-menu-open"
});
},
decrease: function (actual_val, stop_val, step, copyright) {
setTimeout(function () {
if (actual_val == stop_val) {
copyright.className = "copyright-menu-closed";
}
actual_val = actual_val - step;
copyright.style.paddingLeft = parseInt(actual_val) + "px";
this.decrease(actual_val, stop_val, step, copyright);
}, 10);
}
};当我在this.decrease(280, 80, 10, copyright);行调用initCopyrightMoving时,我得到这个错误:
copyright.js:14 Uncaught TypeError: this.decrease is not a function
at HTMLAnchorElement.<anonymous> (copyright.js:14)
at HTMLAnchorElement.dispatch (jquery-1.11.2.min.js:3)
at HTMLAnchorElement.r.handle (jquery-1.11.2.min.js:3)sm能告诉我我哪里做错了吗?而且因为我不能运行脚本的下一部分,你能告诉我decrease函数写得好不好,我的意思是它能正常运行吗?
发布于 2017-08-04 06:19:30
这里的this是您单击的元素$(".sidebar_toggle")。
尝试在jQuery处理程序之前定义var self = this;,并在处理程序内部调用self.decrease
出于类似的原因,setTimeout中的this.decrease也将无法工作。修复是相同的
发布于 2017-08-04 06:20:24
这是因为当this (上下文)在click回调中时,它会发生变化。停止错误的一种方法是保留this的副本并在回调中使用该副本。
initCopyrightMoving: function() {
var _this = this; // some developers use `self`
$(".sidebar_toggle").click(function() {
var copyright = document.getElementById("copyright-text");
if (copyright.className == "copyright-menu-open") {
_this.decrease(280, 80, 10, copyright);
} else {
copyright.className = "copyright-menu-open"
}
});
},JavaScript中的作用域和上下文上的Here's a useful article。
https://stackoverflow.com/questions/45495393
复制相似问题