jquery添加随机类而不重复

时间:2016-01-04 16:52:30

标签: javascript jquery random addclass removeclass

我在我的网站上使用一个函数随机addClass到div。 工作得很好,但我找不到一种方法可以一个接一个地重复同一个类两次(因为有时会添加相同的类,我们可以认为代码不起作用)......

这是我的jquery代码:

$("#switch").click(function(){

var classes = ["vert", "escalier","reverse","demi_escalier","demi_escalier_2","ligne" ];

$("#logo").removeClass().addClass(classes[~~(Math.random()*classes.length)]);

});

任何人都可以帮我这个吗?

感谢

2 个答案:

答案 0 :(得分:1)

如果您希望课程不重复,您可以使用以下内容:

var classes = ["vert", "escalier", "reverse", "demi_escalier", "demi_escalier_2", "ligne"];
var classesCopy = classes.slice();

$('#switch').click(function() {
  if (!classesCopy.length) {
    classesCopy = classes.slice();
  } // once alls classes used up it starts from beginning 
  var classToAdd = classesCopy.splice(Math.floor(Math.random() * classesCopy.length), 1);
  $('.current-class').text('current class: ' + classToAdd);
  $('#logo').removeClass().addClass(classToAdd+'');
});
#logo {
  width: 100px;
  height: 100px;
  background: green;
}
<div class='current-class'></div>
<div id='logo'></div>
<button id='switch'>switch</button>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>

答案 1 :(得分:0)

//put it in an IIFE so the variables are scoped down
(function(){
    //constants, don't need to declare them in the click function over and over
    var classes = ["vert", "escalier","reverse","demi_escalier"
                   ,"demi_escalier_2","ligne" ];
    //keep track of the last class used, -1 initial so no chance of mismatch
    var lastNumber = -1;
    var $logo = $("#logo");

    $("#switch").on('click', function() {
        //get a new index
        var nextClass = Date.now() * 100 % classes.length;;

        //while they match, keep getting a new one
        while (nextClass === lastNumber) {
            nextClass = Date.now() * 100 % classes.length;
        }

        $logo.removeClass().addClass(classes[nextClass]);
        //save it off so we can do the double check again on the next execution
        lastNumber = nextClass;
    });
})();