如何使用JavaScript使“重置”按钮真正起作用?

时间:2018-10-08 21:04:10

标签: javascript html dom

考虑以下代码:

  var animalSound = document.getElementById("animalSound");

重置按钮:

   var resetButton = document.querySelector("#reset");

控制台上的函数表示该值为null

 resetButton.addEventListener("click", function(){
   alert(" clicked button");
 })

它采摘的动物:

 var animals = ["elephant", "dog", "monkey", "zebra", 
           "parakeet", "cat", "pig", "Guerilla", 
           "skunk", "Leapord" ]


 var x = animals[Math.floor(Math.random()*animals.length)];
 animalSound.textContent =  x;

1 个答案:

答案 0 :(得分:0)

我将把选择随机动物的代码放入函数中,并在单击时调用它:

var resetButton = document.querySelector("#reset");

resetButton.addEventListener("click", function(){
  setNewAnimal()
});

// the animals it picks from
 var animals = ["elephant", "dog", "monkey", "zebra", 
           "parakeet", "cat", "pig", "gorilla", 
           "skunk", "leopard" ];

// set random animal
function setNewAnimal() {
   var animalSound = document.getElementById("animalSound");
   var x = animals[Math.floor(Math.random()*animals.length)];
   animalSound.textContent =  x;
 }
 
 setNewAnimal();
<div id="animalSound"></div>
<button id="reset">Reset</button>