简体   繁体   English

为什么我的数组不会回到 0 (javascript)?

[英]why my array won't back to 0 (javascript)?

 var a = ["red", "blue", "green"]; var i = 0 $(".button").click(function() { i++; if (i >= 3) { i = 0; } console.log(i); $("body").addClass(a[i]); console.log(a[i]); });
 .red { background-color: red; } .blue { background-color: blue; } .green { background-color: green; }
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <button type="button" class="button">Click</button>

It can turn from white to blue and green, but if i click the button again it won't turn to red, blue, and green.它可以从白色变成蓝色和绿色,但如果我再次单击按钮,它不会变成红色、蓝色和绿色。 But the console show 1,2,0,1,2,0 and also the color blue, green, red, blue但控制台显示 1,2,0,1,2,0 以及蓝色、绿色、红色、蓝色

Your issue is that you're not ever removing the old class, so eventually the body has all three classes and it just uses the last one.你的问题是你永远不会删除旧类,所以最终身体有所有三个类,它只使用最后一个。 Add添加

$("body").removeClass(a[i]);

to the beginning of your click handler:到您的点击处理程序的开头:

 var a = ["red", "blue", "green"]; var i = 0 $(".button").click(function() { $("body").removeClass(a[i]); i++; if (i >= 3) { i = 0; } console.log(i); $("body").addClass(a[i]); console.log(a[i]); });
 .red { background-color: red; } .blue { background-color: blue; } .green { background-color: green; }
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <body> <button type="button" class="button">Click</button> </body>

This one will add and remove the different colour classes to and from the document and will not affect any other document classes that might have been assigned before.这将在文档中添加和删除不同的颜色类,并且不会影响之前可能已分配的任何其他文档类。

 const a = ["red", "blue", "green"]; ai=-1;a.col=function(){const cl=document.body.classList; cl.remove(this[this.i++]); cl.add(this[this.i%=3]); console.log(this.i,this[this.i]); }; document.querySelector(".button").onclick=ev=>a.col();
 .red { background-color: red; } .blue { background-color: blue; } .green { background-color: green; }
 <button type="button" class="button">Click</button>

Change $("body").addClass(a[i]);更改$("body").addClass(a[i]); to document.body.className = a[i];document.body.className = a[i];

And you don't need jQuery.而且你不需要 jQuery。

Like so:像这样:

 var a = ["red", "blue", "green"]; var i = 0 document.querySelector(".button").addEventListener( 'click', function() { i++; if (i >= 3) { i = 0; } console.log(i); document.body.className = a[i]; console.log(a[i]); });
 .red { background-color: red; } .blue { background-color: blue; } .green { background-color: green; }
 <button type="button" class="button">Click</button>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM