2016-05-29 13 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 Quotesfunction Quoteである必要があります。同様に、new Quotesnew Quoteである必要があります。

これは単なる約束です。

+0

それが問題を解決しました。 – Abk

関連する問題