简体   繁体   English

为什么我的代码中需要“返回假”?

[英]Why is there the need for “return false” in my code?

I have read up on what event bubbling means and understood what it meant, but I am still unable to understand why my code requires "return false". 我已经阅读了事件冒泡的含义,并理解了它的含义,但是我仍然无法理解为什么我的代码要求“ 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;

the return false would prevent the form from submit. return false将阻止表单提交。 You can also use e.preventDefault() in this case (and this is probably what you really want). 在这种情况下,您也可以使用e.preventDefault() (这可能是您真正想要的)。

Anyway, you can simply remove the form tag altogether, it's not necessary. 无论如何,您可以简单地完全删除form标签,这是没有必要的。 (or handle onsubmit instead of onclick/onkeypress if you want to use form ) (如果要使用form则处理onsubmit而不是onclick/onkeypress

Since this is an Enter button in case it is a form in a markup it may trigger submit of the form, I would suggest changing return false; 由于如果是标记中的表单,这是一个Enter按钮,它可能会触发表单的提交,所以我建议将return false;更改为return false; to e.preventDefault(); e.preventDefault(); because it is much more literal at what it is doing, but that's just my opinion 因为它实际上是在做什么,但这只是我的看法

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM