我在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>
按钮的默认类型是提交,为防止表单提交,您必须手动指定type="button"
:
<button type="button" id="btn">Calculate Plan</button>
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>