在我的函数中添加一个类

时间:2017-07-11 15:13:19

标签: jquery css3

我正在上一门课程,要求我制作一个"随机报价生成器"。

我正在尝试添加此类:

div.info p {
  color: #fff;
  font-size: 1em;
}

我在我的jQuery中创建的数组。我完全迷失了。我尝试过添加

.addClass(div.info p)

到我的代码,我认为我应该怎么做,但不知道如何。

到目前为止,这是我的JS:

$(document).ready(function() {
  function getQuote() {
    var quotes = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p" ];
    var author = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p" ];

    $.each($('.info'), function(i, element) {
      $(element).html(quotes[randomNum]);
    });

    var randomNum = Math.floor((Math.random() * quotes.length));
    var randomQuote = quotes[randomNum];
    var randomAuthor = author[randomNum];

    $(".quote").text(randomQuote);
    $(".author").text(randomAuthor);
  }

  $(".btn").on("click", getQuote);
});

2 个答案:

答案 0 :(得分:0)

您的问题是因为每次尝试访问阵列时都需要生成一个新的随机数 - 假设您每次都想要一个不同的结果。试试这个:



function getQuote() {
  var quotes = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p"];
  var author = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p"];

  var random = function(max) {
    return Math.floor((Math.random() * max));
  }
  
  $.each($('.info'), function(i, element) {
    $(element).html(quotes[random(quotes.length)]);
  });

  var randomQuote = quotes[random(quotes.length)];
  var randomAuthor = author[random(author.length)];

  $(".quote").text(randomQuote);
  $(".author").text(randomAuthor);
  
}

$(".btn").on("click", getQuote);

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="info"></div>
<div class="info"></div>
<div class="info"></div>
<div class="info"></div>
<div class="info"></div>
<div class="info"></div>
<div class="info"></div>

Quote:
<div class="quote"></div>

Author:
<div class="author"></div>

<button class="btn">Click me</button>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

不是选择元素,而是添加CSS类选择器,例如 .my-paragraph 并添加所需的样式,然后使用jQuery将该类添加到段落.addClass("my-paragraph")中。假设您要将此样式添加到引号:$(".quote").text(randomQuote).addClass("my-paragraph");

$("p").addClass("my-paragraph");
.my-paragraph {
   color: blue;
   font-size: 1em;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>My paragraph</p>
<p>My other paragraph</p>