I'd like to change the text color using the following code, but I get an error: Uncaught syntax: unexpected string
when .each
is called. I'm not sure what's wrong.
function random_rgb() {
colors = ['8', '9', 'a', 'b', 'c', 'd', 'e', 'f'];
r = colors.eq(Math.floor(Math.random * 8));
g = colors.eq(Math.floor(Math.random * 8));
b = colors.eq(Math.floor(Math.random * 8));
return '#' + r + g + b;
};
$(document).ready({
$("span.number").each(function(){
this.style.color = random_rgb();
});
});
UPDATE
I've created a jsfiddle (forgive me I'm not great w/ this app) https://jsfiddle.net/yrnqr566/
The color turns up black every time.
You have a couple of errors, see this fiddle for the fixes; https://jsfiddle.net/yrnqr566/10/
$(function() {...});
is a better alternative to document.ready...
Also, you need to use Math.random()
with open/close brackets, as this is a function not a property.
Third, you were using .eq()
on an array. []
is the correct syntax.
function random_rgb() {
colors = ['8', '9', 'a', 'b', 'c', 'd', 'e', 'f'];
r = colors[Math.floor(Math.random() * 8)];
g = colors[Math.floor(Math.random() * 8)];
b = colors[Math.floor(Math.random() * 8)];
return '#' + r + g + b;
};
$(function() {
$('span.number').each(function() {
this.style.color = random_rgb();
});
});
Guess you need something like this, you had a few errors in your random_rgb() function
.
Also jquery
way would be $(this).css('color',random_rgb());
function random_rgb() { colors = ['8', '9', 'a', 'b', 'c', 'd', 'e', 'f']; r = colors[Math.floor(Math.random() * 8)]; g = colors[Math.floor(Math.random() * 8)]; b = colors[Math.floor(Math.random() * 8)]; return '#' + r + g + b; } $("span.number").each(function() { this.style.color = random_rgb(); });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <span class="number">Some Long Text</span> <span class="number">Some Long Text</span> <span class="number">Some Long Text</span> <span class="number">Some Long Text</span> <span class="number">Some Long Text</span> <span class="number">Some Long Text</span> <span class="number">Some Long Text</span>
shoud return something like :return rgb(255, 0, 0) or try this:
$(document).ready(function () {
$('div').css('background',randrgb());
})
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.