2017-07-11 125 views
0

我正在學習一門課程,需要我製作「隨機報價生成器」。向我的功能添加班級

我想添加這個類:

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); 
}); 

回答

0

而不是選擇一個元素,添加CSS類選擇,例如,。我段並添加所需的樣式,然後使用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>

+0

所以,如果我正確地理解你,我導入ajax到我的外部codepen。 如果我有我的數組定義爲引號和randomQuotes。 這是否合理 $(「randomQuote」).addClass(「div.info p」)? 編輯:感謝您的快速回復! –

+0

如果你使用[.addClass](https://api.jquery.com/addclass/)方法,你需要使用CSS類選擇器(這裏是一個例子)。當你的函數要迭代數組時,它將會自動用_.addClass_方法添加該樣式。 –

+0

看起來你正在使用jQuery編輯HTML。我對麼? –

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>

+0

羅太感謝你了!非常感謝,但是這裏是項目的鏈接。 https://codepen.io/jsf2008/pen/vZQxPe 我有12個不同的對象,最終我會生成12個不同的新引號每一次。下一步是在jQuery中這樣做。它只是讓替換數組顯示與我遇到問題的同一個類。 –