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>
添加回答
举报