[英]Why is there the need for “return false” in my code?
我已經閱讀了事件冒泡的含義,並理解了它的含義,但是我仍然無法理解為什么我的代碼要求“ return false”。
function init() {
var fireButton = document.getElementById("fireButton");
fireButton.onclick = handleFireButton;
var guessInput = document.getElementById("guessInput");
guessInput.onkeypress = handleKeyPress;
}
function handleFireButton() {
var guessInput = document.getElementById("guessInput");
var guess = guessInput.value;
controller.processGuess(guess);
guessInput.value = "";
}
function handleKeyPress(e) {
var fireButton = document.getElementById("fireButton");
if (e.keyCode === 13) { //13 represent the "Enter" key.
fireButton.click();
return false;
}
}
window.onload = init;
return false
將阻止表單提交。 在這種情況下,您也可以使用e.preventDefault()
(這可能是您真正想要的)。
無論如何,您可以簡單地完全刪除form
標簽,這是沒有必要的。 (如果要使用form
則處理onsubmit
而不是onclick/onkeypress
)
由於如果是標記中的表單,這是一個Enter按鈕,它可能會觸發表單的提交,所以我建議將return false;
更改為return false;
到e.preventDefault();
因為它實際上是在做什么,但這只是我的看法
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.