![](/img/trans.png)
[英]What should I tweak in the Javascript/HTML to make this random quote generator work?
[英]What can't I get this random quote generator to work?
我一直在嘗試制作一個“隨機報價機”,它從 5 個引號的數組中隨機選擇一個引號,並將文本插入網頁上的一個段落中。 機器使用 HTML 和 JavaScript(jQuery)。 鑒於項目是多么簡單,我懷疑我的錯誤很簡單。
這是 HTML:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Random Quote Machine</title>
<script src="jquery.min.js"></script>
<script src="quotes.js"></script>
</head>
<body>
<h1>Mason Cooley Quotes</h1>
<div>
<p id="quote"></p>
</div>
<button id="quoteGen">Generate A Random Quote</button>
</body>
</html>
這是 JavaScript:
var quotes = ["Innocence is thought charming because it offers delightful possibilities for exploitation.",
"Every day begins with an act of courage and hope: getting out of bed.",
"Hatred observes with more care than love does.",
"To understand someone, find out how he spends his money.",
"The educated do not share a common body of information, but a common state of mind."
];
function getQuote() {
return Math.floor(Math.random() * quotes.length);
}
$('#quoteGen').click(function() {
$('#quote').text(quotes[getQuote()]);
});
因為您的腳本包含在head
元素中,所以quoteGen
您嘗試將事件處理程序綁定到它時, DOM 中不存在quoteGen
按鈕。 您需要在body
標記結束之前包含腳本,或者將代碼包裝在 DOM 就緒事件處理程序中,以確保 DOM 在代碼運行時按照您的預期存在。
所以,你可以選擇這個:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Random Quote Machine</title>
</head>
<body>
<h1>Mason Cooley Quotes</h1>
<div>
<p id="quote"></p>
</div>
<button id="quoteGen">Generate A Random Quote</button>
<script src="jquery.min.js"></script>
<script src="quotes.js"></script>
</body>
</html>
...或者,使用 DOM-ready 處理程序,例如:
$(function () {
$('#quoteGen').click(function() {
$('#quote').text(quotes[getQuote()]);
});
});
在#quoteGen dom 節點存在之前設置處理程序。
您需要將包含的quotes.js 移動到文件的末尾,就在/BODY 關閉之前。
或者在文檔准備好后注冊要安裝的處理程序:
$(document).ready(function(){ $('#quoteGen').click(function() { $('#quote').text(quotes[getQuote()]); }); });
這段代碼工作正常。 歸功於所有者。
// Random Quotes
var Quotation=new Array()
Quotation[0] = "Time is of the essence! Comb your hair.";
Quotation[1] = "Sanity is a golden apple with no shoelaces.";
Quotation[2] = "Repent! The end is coming, $9.95 at Amazon.";
Quotation[3] = "Honesty blurts where deception sneezes.";
Quotation[4] = "Pastry satisfies where art is unavailable.";
Quotation[5] = "Delete not, lest you, too, be deleted.";
Quotation[6] = "O! Youth! What a pain in the backside.";
Quotation[7] = "Wishes are like goldfish with propellors.";
Quotation[8] = "Love the river's \"beauty\", but live on a hill.";
Quotation[9] = "Invention is the mother of too many useless toys.";
var Q = Quotation.length;
var whichQuotation=Math.round(Math.random()*(Q-1));
function showQuotation()
{document.write(Quotation[whichQuotation]);}
showQuotation();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.