如何在下面的span中放置arr元素?此外,我不明白当我点击播放按钮时,这些值将如何重新生成。请帮助
<div class="result">
<span class="one"></span>
<span class="two"></span>
<span class="three"></span>
</div>
<button type="submit" class="btn">Play Again</button>
<script>
let sum = Math.floor(Math.random()*100)
const one = document.querySelector(".one")
const two = document.querySelector(".two")
const three = document.querySelector(".three")
one.innerHTML = Math.floor(Math.random()*100)
two.innerHTML = Math.floor(Math.random()*100)
three.innerHTML = Math.floor(Math.random()*100)
let arr = [ one, two, three]
let i = Math.random()*3
arr.splice(i, 0, sum )
const btn = document.querySelector(".btn")
btn.addEventListener("click", function(e){
e.preventDefault()
})
</script>
您需要创建一个可以调用的函数。此外,您还需要将btn
类添加到<button>
中。你可以这样做
let sum = Math.floor(Math.random()*100)
// Move this code in a function so that you can call it again
function regenerate() {
const one = document.querySelector(".one")
const two = document.querySelector(".two")
const three = document.querySelector(".three")
one.innerHTML = Math.floor(Math.random()*100)
two.innerHTML = Math.floor(Math.random()*100)
three.innerHTML = Math.floor(Math.random()*100)
let arr = [ one, two, three]
let i = Math.random()*3
arr.splice(i, 0, sum )
}
regenerate();
const btn = document.querySelector(".btn")
btn.addEventListener("click", function(e){
e.preventDefault()
regenerate();
})
<div class="result">
<span class="one"></span>
<span class="two"></span>
<span class="three"></span>
</div>
<!-- You missed the class btn here -->
<button type="submit" class="btn">Play Again</button>
在js代码之外添加脚本标记
<script>
Your javascript code here…
</script>