【发布时间】:2021-03-16 16:13:36
【问题描述】:
我正在开发一个 非常 简单的 javascript 测验项目,它有一个分数和一个开始按钮,当它被点击时会生成问题。我通过添加一个 onclick 事件侦听器开始在 JS 代码中工作,但它没有按预期工作。这是应该可以工作但不起作用的代码 sn-p,有几个 cmets。请记住,我对 Javascript 非常缺乏经验,所以我可能误用了一些 JS 方法。
function rng() {
return Math.floor(Math.random * 10)
}
let stbt = document.getElementById("start")
stbt.addEventListener("click", function() {
stbt.remove //should remove the start button when it gets clicked.
let q = document.createElement("p") //created an html paragraph.
switch(rng()) {
case 1:
let qc = document.createTextNode("What is the capital of Chile?")
q.appendChild(qc) /*this should theoretically insert text into the html paragraph that gets created when the start button gets clicked,
the switch statement that is switching the simple rng function should make it so that questions get generated randomly.*/
break;
case 2:
let qc = document.createTextNode("What is the highest mountain in Britain?")
q.appendChild(qc)
break;
case 3:
let qc = document.createTextNode("What is the smallest country in the world?")
q.appendChild(qc)
break;
case 4:
let qc = document.createTextNode("Alberta is a province of which country?")
q.appendChild(qc)
break;
case 5:
let qc = document.createTextNode("How many countries still have the shilling as currency?")
q.appendChild(qc)
break;
case 6:
let qc = document.createTextNode("Which is the only vowel not used as the first letter in a US State?")
q.appendChild(qc)
break;
case 7:
let qc = document.createTextNode("What is the largest country in the world?")
q.appendChild(qc)
break;
case 8:
let qc = document.createTextNode("Where would you find the River Thames?")
q.appendChild(qc)
break;
case 9:
let qc = document.createTextNode("What is the hottest continent on Earth?")
q.appendChild(qc)
break;
case 0:
let qc = document.createTextNode("What is the longest river in the world?")
q.appendChild(qc)
break;
}
})
【问题讨论】:
-
stbt.remove()q 附加到任何内容,这就是它不显示的原因。 -
您还缺少
Math.random()上的括号,并且您不能多次声明qc,您需要在switch之外声明一次,然后在其中分配它相关的case。正如异端猴子所说,你永远不会将<p>元素附加到任何东西上。 -
你能简化一下吗?也许只有一个案例?
标签: javascript onclick switch-statement