Javascript class name manipulation not working

This question already has an answer here:

  • Change an element's class with JavaScript 30 answers

  • 你应该用“绑定”来调用你的函数来保持“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.

    链接地址: http://www.djcxy.com/p/25210.html

    上一篇: 如何在使用javascript的元素的类之间切换?

    下一篇: Javascript类名称操作不起作用