2017-09-04 49 views
0

试图使其与类.book的每个div都从数组中分配随机字体。这是到目前为止我的代码向类中的每个元素添加随机字体

var fonts = ['Gloria Hallelujah', 'Sedgwick Ave', 'Gochi Hand', 'Patrick Hand', 'Kalam', 'Rock Salt', 'Neucha', 'Caveat Brush', 'Schoolbell']; 
var randomfont = fonts[Math.floor(Math.random() * fonts.length)]; 
$(".book").style.fontFamily = randomfont; 

我得到的错误是:Uncaught TypeError: Cannot set property 'fontFamily' of undefined

任何人都知道我做错了吗?

+1

尝试'$( “书 ”),CSS(“ FONT-FAMILY”,randomfont);' – Airwavezx

+0

请发表你的HTML –

回答

2

$(".book")返回一个jquery数组。例如,设置第一个可以使用:

$(".book")[0].style.fontFamily = 

您可以通过$(".book")需要循环得到DOM元素:

$(".book").each(function() { 
    var randomfont = fonts[Math.floor(Math.random() * fonts.length)]; 
    this.style.fontFamily = randomfont; 
}); 

(除非你的意思是他们都设置为相同的字体,其中在环路外设置randomfont)。

0

这是因为您试图直接在jQuery对象而不是DOM元素上设置fontFamily。

要么使用jQuery的css方法或使用get/阵列选择检索的DOM元素。

在你想要做的每一个元素,另一方面,所以你需要使用each这样的:

//const fonts = ['Gloria Hallelujah', 'Sedgwick Ave', 'Gochi Hand', 'Patrick Hand', 'Kalam', 'Rock Salt', 'Neucha', 'Caveat Brush', 'Schoolbell']; 
 
const fonts = ['Helvetica', 'Arial', 'Verdana', 'Courier', 'Courier New']; 
 

 
$('.book').each(function(item) { 
 
    const randomfont = fonts[Math.floor(Math.random() * fonts.length)]; 
 
    this.style.fontFamily = randomfont; 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<div class="book">Test 1</div> 
 
<div class="book">Test 2</div> 
 
<div class="book">Test 3</div> 
 
<div class="book">Test 4</div> 
 
<div class="book">Test 5</div> 
 
<div class="book">Test 6</div>

0

希望这将有助于。只需使用document.getElementById('')调用该ID,然后设置字体值即可。

var fonts = ['Impact,Charcoal,sans-serif', 'Sedgwick Ave', ' Helvetica', 'Patrick Hand', 'Kalam', 'Rock Salt', 'Neucha', 'Caveat Brush', 'Schoolbell']; 
var randomfont = fonts[Math.floor(Math.random() * fonts.length)]; 
alert(randomfont); 
var val=document.getElementById("book").style.fontFamily = randomfont; 
+0

不会被作为OP想要的设置由*班上做*不* ID*。含义是有多个要设置的元素,ID应该是唯一的。 –

相关问题