簡體   English   中英

為什么我的代碼中需要“返回假”?

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM