Javascript class name manipulation not working
This question already has an answer here:
你应该用“绑定”来调用你的函数来保持“this”的范围。
window.setTimeout(
function(){
this.className = 'closeMenuButtonNotActive';
}.bind(this),
500);
That's because this
is refering to window
on this function:
window.setTimeout(function() {
// Wrong this
this.className = 'closeMenuButtonNotActive';
},500);
Instead you could do
var elem = this;
window.setTimeout(function() {
elem.className = 'closeMenuButtonNotActive';
},500);
Of if you don't want to pollute the global scope:
(function(elem) {
window.setTimeout(function() {
elem.className = 'closeMenuButtonNotActive';
},500);
)(this);
Anyway, to prevent further problems that are hard to debug, you should really consider at least using a function in the HTML <div onmouseup="doStuff(this)">
and define doStuff from the javascript code. Or even better, add the mouse events listeners directive from the code.
上一篇: 如何在使用javascript的元素的类之间切换?
下一篇: Javascript类名称操作不起作用