2016-05-29 104 views
0

我已經嘗試了幾種方法在html段落中隨機打印此打印件,但它無法正常工作。
有人可以幫我解決這個問題嗎?無法正確輸出Javascript到html

var randomPicker = Math.floor(Math.random() * 5); 
var quotesArray = []; 

function Quotes(quote, author) { 
    this.quote = quote; 
    this.author = author; 
} 

quotesArray[0] = new Quotes("Great minds discuss ideas; average minds discuss events; small minds discuss people.", "Eleanor Roosevelt"); 
quotesArray[1] = new Quotes("To be yourself in a world that is constantly trying to make you something else is the greatest accomplishment.", "Ralph Waldo Emerson"); 
quotesArray[2] = new Quotes("Great things are done by a series of small things brought together.", "Vincent Van Gogh"); 
quotesArray[3] = new Quotes("Some are born great, some achieve greatness, and some have greatness thrust upon them.", "William Shakespeare"); 
quotesArray[4] = new Quotes("A tiger does not shout its tigritude, it acts.", "Wole Soyinka"); 
quotesArray[5] = new Quotes("Thinking start with a problem and ends in a solution.", "Dr. Edward de Bono"); 


var rand = quotesArray[randomPicker]; 

function printQuote(){ 
for (var q in rand){ 

console.log(rand[q]); //works well but 

//this 
// document.getElementById("msg").innerHTML = rand[q]; 
//not working... 
    } 
} 
//this also not working... 
document.getElementById("msg").innerHTHL = printQuote(); 

在此先感謝。

+0

我們可以看到你的HTML嗎? –

回答

0

它沒有工作的原因是你的quotesArray的元素不是字符串,而是對象本身。您需要訪問這些對象內部的屬性以獲取字符串。

var randomPicker = Math.floor(Math.random() * 5); 
 
var quotesArray = []; 
 

 
function Quotes(quote, author) { 
 
    this.quote = quote; 
 
    this.author = author; 
 
} 
 

 
quotesArray[0] = new Quotes("Great minds discuss ideas; average minds discuss events; small minds discuss people.", "Eleanor Roosevelt"); 
 
quotesArray[1] = new Quotes("To be yourself in a world that is constantly trying to make you something else is the greatest accomplishment.", "Ralph Waldo Emerson"); 
 
quotesArray[2] = new Quotes("Great things are done by a series of small things brought together.", "Vincent Van Gogh"); 
 
quotesArray[3] = new Quotes("Some are born great, some achieve greatness, and some have greatness thrust upon them.", "William Shakespeare"); 
 
quotesArray[4] = new Quotes("A tiger does not shout its tigritude, it acts.", "Wole Soyinka"); 
 
quotesArray[5] = new Quotes("Thinking start with a problem and ends in a solution.", "Dr. Edward de Bono"); 
 

 

 
var rand = quotesArray[randomPicker]; 
 

 
function printQuote() { 
 
    document.getElementById("quote").innerHTML = rand.quote; 
 
    document.getElementById("author").innerHTML = rand.author; 
 
} 
 

 
printQuote();
<p id="quote"></p> 
 
<p id="author"></p>

編輯:創建在JavaScript中一個新的對象,它可能是一個更好的主意,用奇異的名字對象名稱,而不是複數。

function Quotes應該是function Quote。同樣,new Quotes應該是new Quote

這只是一個約定。

+0

解決了這個問題。 – Abk