質問

http://jsfiddle.net/9UQwM/1/

the script removes class from the elements in an alternating pattern,

most importantly why?

and what can be done to fix the problem?

Object.prototype.removeClass = function (class_name) {
    if (this.length) {
        for (i = 0; i < this.length; i++) {
            this[i].classList.remove(class_name);
        }
    }
}
document.getElementsByClassName("test").removeClass("test");
役に立ちましたか?

解決

Because when you delete, the next index moves down one. Loop in the opposite direction.

for (var i = this.length - 1; i >= 0; i--) { ... }

http://jsfiddle.net/9UQwM/2/

Using a while loop might bring more into it

Object.prototype.removeClass = function(class_name) {
    if (this.length) {
        while(this.length>0) {
            console.log(this.length);
            this[0].classList.remove(class_name);
        }
    }
}
document.getElementsByClassName("test").removeClass("test");

The output would be 7,6,5,4,3,2,1

http://jsfiddle.net/9UQwM/4/

So this is updated when you remove the class

他のヒント

I found another workaround than was described by @epascarello. Making the pure JS array out of this does the job well:

var that = Array.prototype.slice.call(this);
for (var i = 0; i < that.length; i++) {
    that[i].classList.remove(class_name);
}

DEMO: http://jsfiddle.net/9UQwM/3/

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top