将类添加到元素jquery EDITED中

时间:2016-07-19 11:33:00

标签: javascript jquery css

2º编辑

认为它已经解决了,但事实并非如此。当一个页面加载时我想为一些元素添加一个类(在这种情况下是按钮),现在我的代码是:

        $("button").each(function(index){       
            // add the class
            setTimeout(function(){
                $(this).addClass("varrimento");
            }.bind(this),index*5000);
            // remove the class
            setTimeout(function(){
                $(this).removeClass("varrimento");
            }.bind(this),(index+1)*5000); 
        });

此代码将“varrimento”类逐个添加到每个按钮5秒,但它有2个问题。

  • 当我更改页面并返回初始页面时,它就像是 第一次访问的setTimeout在它仍在运行的页面上,依此类推 第二次访问“varrimento”的代码,它被添加到按钮中 再次,他们不像第一次访问那样一个接一个。

  • 在某些页面中,不知道为什么,添加课程需要很长时间 对元素。 ex:在我访问页面之后的页面“索引”上, class会立即添加到第一个按钮,但会更改为第二个按钮 页面(代码是相同的,唯一不同的是数量 按钮)第一个按钮需要15秒才能上课。

连续第二天试图解决这个问题,但无法弄明白。任何帮助人?

1 个答案:

答案 0 :(得分:1)

将您的超时变量保存在localStorage中,然后将其删除 -

var timeout = setTimeout(auto_reload, 90000);
    localStorage.setItem("timeout", timeout);

var timeout = localStorage.getItem("timeout");
            clearTimeout(timeout);