【问题标题】:Apply a random class to an element [duplicate]将随机类应用于元素[重复]
【发布时间】:2012-07-28 16:14:45
【问题描述】:

可能重复:
Apply a random class to every element specified

是否可以获取页面上的所有“a”元素并使用 javascript 将“.pink”、“.blue”或“.yellow”类随机应用于每个 a 元素?我想在我的页面上有不同颜色的链接,但同样随机。我不知道该怎么做,所以我没有任何脚本可以提供。

【问题讨论】:

    标签: javascript jquery hyperlink


    【解决方案1】:

    当您按照标签中的说明使用 jQuery 时,这是一个可能的解决方案:

    // when document is loaded
    $(document).ready(function () {
    
        // set classes
        var classes     = new Array ('pink', 'blue', 'green');
    
        // calculate length once, as this will never change
        var length      = classes.length;
    
        // select all a-tags
        var links       = $('a');
    
        // loop through all a-tags and apply color randomly
        $.each( links, function(key, value) {
            // get random value/class-name from array and add it using the addClass function
            $(value).addClass( classes[ Math.floor ( Math.random() * length ) ] );
        });
    
    });
    

    cmets 应该明确它的作用。

    Try it

    【讨论】:

    • 你真的是说$.each吗?
    • 是的,有什么问题吗? :)
    • 为什么不$('a').each(function() { ... $(this).addClass(...) ... }?这就是 jQuery 的美妙之处。
    • 确定颜色设置一次的方法是什么?您的代码很好,但有时会在多个元素上设置相同的颜色。
    【解决方案2】:

    Math.random() 将返回一个介于 0 和 1 之间的随机浮点数。要将其转换为数组索引,请将其乘以数组的大小并取 Math.floor 向下舍入:

    var arr = ['red','green','blue'];
    var idx = Math.floor(Math.random() * arr.length);
    
    alert(arr[idx]);
    

    Math.random()

    【讨论】:

      【解决方案3】:

      您可以将您的类放入数组中,然后遍历“A”标签并为每个类分配随机索引(使用 Math.random()):

      var colorClasses = ['pink', 'blue', 'yellow'];
      $("a").each(function(e){
          classIndex = Math.floor(Math.random() * colorClasses.length);
          $(this).addClass(colorClasses[classIndex]);
      });​
      

      现场演示:http://jsfiddle.net/ALngA/2/

      【讨论】:

        【解决方案4】:
        var colors = ['pink', 'blue', 'yellow']
        $('a').each(function () {
          var rand = ~~(Math.random() * colors.length)
          $(this).addClass(colors[rand])
        })
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2010-12-04
          • 2011-12-02
          • 2017-12-21
          • 1970-01-01
          • 1970-01-01
          • 2012-08-02
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多