2012-12-10 44 views
-1
隨機文本

我試圖讓刷新一個簡單的文字變化:上刷新

<strong>Title</strong> 
<p id="myQuote">Slogan</p> 

而就刷新了「口號」部分的變化:

var myQuotes = new Array(); 
myQuotes[0] = "To be or not to be"; 
myQuotes[1] = "The only thing we have to fear is fear itself"; 
myQuotes[2] = "Give me liberty or give me death"; 

var myRandom = Math.floor(Math.random()*myQuotes.length); 

$('#myQuote').html(myQuotes[myRandom]); 
+0

你確保jQuery是進口的,你的代碼被稱爲在DOM準備回調?你有錯誤嗎? –

+1

適用於我:http://codepen.io/joe/pen/BsoGH – EricG

+0

在加載DOM之前,您無法選擇DOM元素;將'$('#myQuote')。html(myQuotes [myRandom]);'放入'$(document).ready(function(){...})'中。 – apsillers

回答

0

我的猜測是不加載的jQuery ....

if (jQuery) { 
    alert('jQuery is loaded'); 
} else { 
    alert('not loaded'); 
} 

然後檢查你正在從隨機函數的值。

var myRandom = Math.floor(Math.random()*myQuotes.length); 

alert(myQuotes[myRandom]); //Add this to your code 

$('#myQuote').html(myQuotes[myRandom]); 
1

您不能選擇或操縱DOM元素直到DOM被加載。

將您的$('#myQuote').html打包在$(document).ready(function() { ... })之內,如this fiddle所示。

或者,將<script>標記放在<body>的底部,以便在DOM的其餘部分之後加載它。 (見Unobtrusive JavaScript: <script> at the top or the bottom of the HTML code?您的加載時間的選擇進一步的討論。)

+1

其實你可以:http://jsfiddle.net/Hn6fL/2/你只需要在你的目標特定元素被加載後運行代碼。 – Christophe

+0

你是編輯我的小提琴還是用我的代碼創建自己的小提琴?加載時間下拉必須設置爲「無包裝(頭)」,否則無論如何它都被jsfiddle包裝。這裏是一個非工作小提琴:http://jsfiddle.net/T3htp/ – apsillers

+0

你是說即使你選擇無包裝(正文)的代碼獲取包裝? – Christophe

0

替換以下,以避免在你的腳本

http://jsfiddle.net/TYEGh/

$('#myQuote').html(myQuotes[myRandom]); 

使用jQuery與

document.getElementById('myQuote').innerHTML= myQuotes[myRandom];