原型 - 删除类,到由 ClassName 选择的元素 [英] prototype - remove class, to elements selected by ClassName
本文介绍了原型 - 删除类,到由 ClassName 选择的元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
脚本以交替模式从元素中删除类,
the script removes class from the elements in an alternating pattern,
最重要的是为什么?
以及如何解决问题?
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--) { ... }
使用 while 循环可能会带来更多内容
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");
输出将是 7,6,5,4,3,2,1
The output would be 7,6,5,4,3,2,1
所以 this
在你删除类时更新
So this
is updated when you remove the class
这篇关于原型 - 删除类,到由 ClassName 选择的元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文