1 回答

TA貢獻1818條經驗 獲得超8個贊
document.write()在現代 JavaScript 中的用例非常有限,絕對不應該像您正在使用的那樣使用它。任何教你這個的人顯然并不真正了解 JavaScript 和文檔對象模型。
至于你的問題,你需要決定“何時”運行 JavaScript,然后為該時刻設置一個事件處理程序。
請參閱下面的內聯評論。
// Prepare your static data ahead of time and store it in an array.
// Here we have one array, with 3 child arrays inside of it (one for each
// question.
let facts = [
? ?["The FIRST music video on MTV was for the song 'Video Killed the Radio Star', by the English new wave group The Buggles, and premiered on August 1, 1981 at 12:01 AM",
"The FIRST McDonald's restauarant opened in San Bernardino, CA, on May 15, 1940",
"The FIRST ever mobile phone call was made on April 3, 1973, by Martin Cooper, a senior engineer at Motorola",
"The FIRST photo of lightning was taken on September 2, 1882, by William Jennings, who wanted to know if lightning really had a zigzag form",
"The FIRST person to ever go down Niagara Falls in a barrel was 63-year-old Annie Edison Taylor, who was a widowed teacher. She made no money from her stunt",
"The FIRST Apple computer, developed and designed by Steve Wozniak and presented by Steve Jobs, was released on April 11, 1976"
? ?],
? ?
? ?[
? ? "some fact",
? ? "some fact",
? ? "some fact"
? ?],
? ?[
? ? "some other fact",
? ? "some other fact",
? ? "some other fact"
? ?]
];
// Set up a function that will run when the button is clicked
document.querySelector("button").addEventListener("click", getFacts);
function getFacts(){
? // Always supply the second, optional (radix) argument to parseInt()
? let number = parseInt(prompt("Enter any number between from 1-5"), 10);
? // Prevent bad numbers
? if (number > facts.length || number < 0){
? ? alert("Bad input! Try again.");
? ? return;
? }
? // Get a reference to the <div> in the document where the output should go
? let output = document.getElementById("facts");
? // Separate each string in the appropriate sub-array with <br>
? // and populate the output element with all of them
? output.innerHTML = facts[number-1].join("<br>");
}
<button>Get the facts!</button>
<!-- This empty div will eventually be populated with
? ? ?the relevant facts. -->
<div id="facts"></div>
添加回答
舉報