Console.log()和el.innerText立即重置(帮助)

问题描述 投票:0回答:1

我在html文件中有这个简单的模板。每次单击按钮时,它应该记录单击事件并在#result元素中打印“ [NodeList]”,但不会。实际上,它会打印几毫秒,然后再次将其删除。与console.log(e)相同。我记录了这种行为:链接到视频:https://drive.google.com/file/d/1B7TycQxZPi0dqx7Try6kUZM3pcJs0ILW/view

有人可以提出修复建议吗?

document.getElementById("btn").addEventListener("click", e => {
  console.log(e);
  result.innerText = document.getElementsByName("day");
});
<h1>Your Day Plan:</h1>
<p>Enter your day</p>
<form>
  <input type="radio" id="mon" name="day" value="mon" />
  <label for="mon">mon</label><br />
  <input type="radio" id="tue" name="day" value="tue" />
  <label for="tue">tue</label><br />
  <input type="radio" id="wed" name="day" value="wed" />
  <label for="wed">wed</label><br />
  <input type="radio" id="thu" name="day" value="thu" />
  <label for="thu">thu</label><br />
  <input type="radio" id="fri" name="day" value="fri" />
  <label for="fri">fri</label><br />
  <button id="btn">Calculate Plan</button>
</form>
<h5 id="result"></h5>
javascript dom console console.log
1个回答
0
投票

按钮的默认类型是提交,为防止表单提交,您必须手动指定type="button"

<button type="button" id="btn">Calculate Plan</button>

OR:使用event.preventDefault()

Event接口的preventDefault()方法告诉用户代理,如果未明确处理事件,则不应该照常执行其默认操作。

<h1>Your Day Plan:</h1>
<p>Enter your day</p>
<form>
  <input type="radio" id="mon" name="day" value="mon" />
  <label for="mon">mon</label><br />
  <input type="radio" id="tue" name="day" value="tue" />
  <label for="tue">tue</label><br />
  <input type="radio" id="wed" name="day" value="wed" />
  <label for="wed">wed</label><br />
  <input type="radio" id="thu" name="day" value="thu" />
  <label for="thu">thu</label><br />
  <input type="radio" id="fri" name="day" value="fri" />
  <label for="fri">fri</label><br />
  <button id="btn">Calculate Plan</button>
</form>
<h5 id="result"></h5>

<script>

  document.getElementById("btn").addEventListener("click", e => {
    console.log(e);
    result.innerText = document.getElementsByName("day");
    event.preventDefault();
  });

</script>
© www.soinside.com 2019 - 2024. All rights reserved.