2016-03-24 18 views
3

次のコードを使用してテキストの色を変更したいと思いますが、.eachが呼び出されたときにエラー:Uncaught syntax: unexpected stringが表示されます。私は何が間違っているのか分かりません。jqueryを使用してテキストを擬似ランダム色に変更します

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

私はhttps://jsfiddle.net/yrnqr566/

色は黒たびにアップになります(私はこのアプリ/ W素晴らしいではありませんよ私を許して)jsfiddleを作成しました。

+1

あなたのHTMLはどんな感じでしょうか?このエラーを誇示するためのフィドルを手に入れましたか? – Novocaine

+0

更新をご覧ください。 – tidelake

+1

'Math.random'は関数で、' Math.random() 'を呼び出すには括弧を使う必要があります。 –

答えて

4

あなたは修正のために、このフィドルを参照してください、エラーのカップルを持っています。 https://jsfiddle.net/yrnqr566/10/

$(function() {...});がdocument.readyするためのより良い代替手段です...

はまた、あなたは、この関数ではない財産であるとして、オープン/クローズブラケットとMath.random()を使用する必要があります。

第3に、アレイ上で.eq()を使用していました。 []は正しい構文です。

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

のようなものを返すshoud:リターンRGB(255、0、0) またはこれを試してみてください。

$(document).ready(function() { 

    $('div').css('background',randrgb()); 
}) 
+0

申し訳ありませんが、関数はrgbと言っていますが、16進値が必要です。 – tidelake

2

は、あなたがあなたのrandom_rgb() functionでいくつかのエラーを持っていた、このようなものが必要と思います。
またjquery方法は$(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>

関連する問題