ボタンに私の関数GetQuotes()
を追加しようとしています。ボタンをクリックするたびに、新しいテキストが表示されます。この場合は新しい引用符が表示されます。現在のところ、ボタンには回答が表示されるのはundefined
です。私の関数は未定義の値だけを返すようです。
私のロジックは、引用符の文字列で配列を作成することでした。最初にfor
ループを使用してランダムな引用符を生成して表示しようとしました。しかし、それは明らかに意味をなさない。私はランダム引用符を生成するためにMath.random()
を使用しました。私はそれから、クラスをstuff
というクラスに追加しようとしました。このボタンはquotes
と呼ばれます。ボタンをクリックすると、h2
のテキストが変更されます。ここで
はJavascriptを次のとおりです。ここで
function getQuotes(){
var quotes = [
"Thousands of candles can be lighted from a single candle, and the life of the candle will not be shortened. Happiness never decreases by being shared.Buddha",
"Happiness is the art of never holding in your mind the memory of any unpleasant thing that has passed.Unknown",
"To be happy, we must not be too concerned with others.Albert Camus",
"If you want happiness for an hour — take a nap.If you want happiness for a day — go fishing.If you want happiness for a year — inherit a fortune.If you want happiness for a lifetime — help someone else."
]
var result = quotes[Math.floor(Math.random() * quotes.length)];
document.getElementById("stuff").innerHTML = result;
}
はjQueryのです:
$(document).on('click', '#quotes', function() {
document.getElementById("stuff").innerHTML = getQuotes();
});
そしてHTML:
<div class="row">
<div class="col-12-xs">
<h2 id="stuff" class="text-center"><em> Here is some Text </em> </h2>
</div>
</div>
$( '#もの') - : あなたは、コードに次の変更を行うことができます。html(getQuotes()); – circusdei
あなたの関数内で、 'document.getElementById(" stuff ")を削除してinnerHTML = result;'を返し、 'return result; 'に置き換えてください –
それがなぜ機能するのか説明できますか? – Codes316