【问题标题】:How would I use JavaScript to make the reset button actually work?我将如何使用 JavaScript 使重置按钮真正起作用?
【发布时间】:2018-10-09 08:28:07
【问题描述】:

考虑以下代码:

  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;

【问题讨论】:

  • 那么“实际工作”意味着什么:您想要实现什么目标以及出了什么问题?
  • “我的控制台显示该值为空的函数”可能与Why does jQuery or a DOM method such as getElementById not find the element?重复
  • 我正在尝试设置一个值,所以当我单击按钮时它会重置列表并重新开始游戏
  • @JonathanRys - 恭喜你拥有读心术。 :-)
  • 提供所有上下文的minimal reproducible example 总是很有帮助的。如果没有您的 HTML,我们不知道您是否正确选择了元素。

标签: javascript html dom


【解决方案1】:

我会将选择随机动物的代码放入一个函数中并在点击时调用它:

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>

【讨论】:

  • 那么请选择我的答案作为正确答案。谢谢!
猜你喜欢
  • 1970-01-01
  • 2014-07-11
  • 2022-11-18
  • 1970-01-01
  • 2021-02-25
  • 1970-01-01
  • 2018-10-25
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多