Javascript 何时使用 preventDefault() 与 Return false?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/30473581/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 05:14:03  来源:igfitidea点击:

When to use PreventDefault( ) vs Return false?

javascriptpreventdefault

提问by Mike

Firstly, in JavaScript's event model, you will come across a concept called as event bubbling (which makes an event to propagate from child element to a parent element). In order to avoid such kind of bubbling effect, many developers use an event method called stopPropagation( ). Alternatively, developers have started to use return falsestatement to stop such propagation. Now, there is another terminology called preventDefault( ). As the name indicates, this method prevents any default behavior of an element to trigger. Best use case is to prevent an anchor tag to open a link.

首先,在 JavaScript 的事件模型中,您会遇到一个称为事件冒泡的概念(它使事件从子元素传播到父元素)。为了避免这种冒泡效应,许多开发人员使用了一种名为 的事件方法stopPropagation( )。或者,开发人员已经开始使用 return false语句来阻止这种传播。现在,还有另一个术语称为 preventDefault( )。顾名思义,此方法可防止触发元素的任何默认行为。最佳用例是防止锚标签打开链接。

You may come across a scenario where you would like to prevent the anchor tag from opening a link (default behavior) as well as stop the event from going up to the parent. In such situation, instead of writing two lines of code, you can get it done in single line i.e; return false

您可能会遇到这样一种情况,即您希望阻止锚标记打开链接(默认行为)以及阻止事件上升到父级。在这种情况下,您可以在一行中完成,而不是编写两行代码,即;return false

回答by Keval Bhatt

return false;

返回假;



return false;does 3 separate things when you call it:

return false;当你调用它时会做 3 件不同的事情:

  1. event.preventDefault()– It stops the browsers default behaviour.
  2. event.stopPropagation()– It prevents the event from propagating (or “bubbling up”) the DOM.
  3. Stops callback execution and returns immediately when called.
  1. event.preventDefault()– 它停止浏览器的默认行为。
  2. event.stopPropagation()– 它可以防止事件传播(或“冒泡”)DOM。
  3. 停止回调执行并在调用时立即返回。

Note that this behaviour differs from normal (non-jQuery) event handlers, in which, notably, return falsedoes not stop the event from bubbling up.

请注意,此行为与普通(非 jQuery)事件处理程序不同,在普通(非 jQuery)事件处理程序中,值得注意的是,return false它不会阻止事件冒泡。

preventDefault();

防止默认();



preventDefault();does one thing: It stops the browsers default behaviour.

preventDefault();做一件事:它停止浏览器的默认行为。

When to use them?

什么时候使用它们?



We know what they do but when to use them? Simply it depends on what you want to accomplish. Use preventDefault();if you want to “just” prevent the default browser behaviour. Use return false; when you want to prevent the default browser behaviour and prevent the event from propagating the DOM. In most situations where you would use return false; what you really want is preventDefault().

我们知道它们做什么,但什么时候使用它们?简单地说,这取决于你想要完成什么。使用preventDefault();,如果你想“只是”防止默认浏览器的行为。使用 return false; 当您想要阻止默认浏览器行为并阻止事件传播 DOM 时。在大多数情况下,您将使用 return false;你真正想要的是preventDefault()

Examples:

例子:



Let's try to understand with examples:

让我们试着用例子来理解:

We will see pure JAVASCRIPT example

我们将看到纯 JAVASCRIPT 示例

Example 1:

示例 1:

<div onclick='executeParent()'>
  <a href='http://stackoverflow.com' onclick='executeChild()'>Click here to visit stackoverflow.com</a>
</div>
<script>
  function executeChild() {
    alert('Link Clicked');
  }

  function executeParent() {
    alert('div Clicked');
  }
</script>

Run the above code you will see the hyperlink ‘Click here to visit stackoverflow.com‘now if you click on that link first you will get the javascript alert Link ClickedNext you will get the javascript alert div Clickedand immediately you will be redirected to stackoverflow.com.

运行上面的代码,您现在将看到“单击此处访问 stackoverflow.com”的超链接,如果您首先单击该链接,您将获得 javascript 警报链接 单击下一步您将获得 javascript 警报div 单击,然后您将立即被重定向到stackoverflow.com。

Example 2:

示例 2:

<div onclick='executeParent()'>
  <a href='http://stackoverflow.com' onclick='executeChild()'>Click here to visit stackoverflow.com</a>
</div>
<script>
  function executeChild() {
    event.preventDefault();
    event.currentTarget.innerHTML = 'Click event prevented'
    alert('Link Clicked');
  }

  function executeParent() {
    alert('div Clicked');
  }
</script>

Run the above code you will see the hyperlink ‘Click here to visit stackoverflow.com‘ now if you click on that link first you will get the javascript alert Link ClickedNext you will get the javascript alert div ClickedNext you will see the hyperlink ‘Click here to visit stackoverflow.com‘ replaced by the text ‘Click event prevented‘ and you will notbe redirected to stackoverflow.com. This is due > to event.preventDefault() method we used to prevent the default click action to be triggered.

运行上面的代码,您现在将看到“单击此处访问 stackoverflow.com”的超链接,如果您先单击该链接,您将获得 javascript 警报链接 单击下一步您将获得 javascript 警报div 单击下一步您将看到超链接 '单击此处访问 stackoverflow.com' 替换为文本“阻止的单击事件”,您将不会被重定向到 stackoverflow.com。这是由于 > 我们用来防止触发默认点击操作的 event.preventDefault() 方法。

Example 3:

示例 3:

<div onclick='executeParent()'>
  <a href='http://stackoverflow.com' onclick='executeChild()'>Click here to visit stackoverflow.com</a>
</div>
<script>
  function executeChild() {
    event.stopPropagation();
    event.currentTarget.innerHTML = 'Click event is going to be executed'
    alert('Link Clicked');
  }

  function executeParent() {
    alert('div Clicked');
  }
</script>

This time if you click on Link the function executeParent() will not be called and you will not get the javascript alert div Clickedthis time. This is due to us having prevented the propagation to the parent div using event.stopPropagation() method. Next you will see the hyperlink ‘Click here to visit stackoverflow.com‘ replaced by the text ‘Click event is going to be executed‘ and immediately you will be redirected to stackoverflow.com. This is because we haven't prevented the default click action from triggering this time using event.preventDefault() method.

这次如果你点击链接,函数 executeParent() 将不会被调用,你不会得到 javascript alert div Clicked这次。这是因为我们使用 event.stopPropagation() 方法阻止了传播到父 div。接下来,您将看到超链接“单击此处访问 stackoverflow.com”被文本“将要执行单击事件”替换,并且您将立即被重定向到 stackoverflow.com。这是因为我们没有使用 event.preventDefault() 方法阻止默认点击操作这次触发。

Example 4:

示例 4:

<div onclick='executeParent()'>
  <a href='http://stackoverflow.com' onclick='executeChild()'>Click here to visit stackoverflow.com</a>
</div>
<script>
  function executeChild() {
    event.preventDefault();
    event.stopPropagation();
    event.currentTarget.innerHTML = 'Click event prevented'
    alert('Link Clicked');
  }

  function executeParent() {
    alert('Div Clicked');
  }
</script>

If you click on the Link, the function executeParent() will not be called and you will not get the javascript alert. This is due to us having prevented the propagation to the parent div using event.stopPropagation() method. Next you will see the hyperlink ‘Click here to visit stackoverflow.com‘ replaced by the text ‘Click event prevented‘ and you will not be redirected to stackoverflow.com. This is because we have prevented the default click action from triggering this time using event.preventDefault() method.

如果您单击链接,则不会调用函数 executeParent() 并且您不会收到 javascript 警报。这是因为我们使用 event.stopPropagation() 方法阻止了传播到父 div。接下来,您将看到超链接“单击此处访问 stackoverflow.com”被文本“阻止单击事件”替换,并且您不会被重定向到 stackoverflow.com。这是因为我们使用 event.preventDefault() 方法阻止了这次触发默认点击操作。

Example 5:

示例 5:

For return false I have three examples and all appear to be doing the exact same thing (just returning false), but in reality the results are quite different. Here's what actually happens in each of the above.

对于 return false,我有三个示例,它们似乎都在做完全相同的事情(只是返回 false),但实际上结果却大不相同。以下是上述每一项中实际发生的情况。

cases:

案例:

  1. Returning falsefrom an inline event handler prevents the browser from navigating to the link address, but it doesn't stop the event from propagating through the DOM.
  2. Returning falsefrom a jQuery event handler prevents the browser from navigating to the link address and it stops the event from propagating through the DOM.
  3. Returning falsefrom a regular DOM event handler does absolutely nothing.
  1. 从内联事件处理程序返回false 会阻止浏览器导航到链接地址,但不会阻止事件通过 DOM 传播。
  2. 从 jQuery 事件处理程序返回false 会阻止浏览器导航到链接地址,并阻止事件通过 DOM 传播。
  3. 从常规 DOM 事件处理程序返回false绝对没有任何作用。

Will see all three example.

将看到所有三个示例。

  1. Inline return false.
  1. 内联返回假。

<div onclick='executeParent()'>
  <a href='http://stackoverflow.com' onclick='return false'>Click here to visit stackoverflow.com</a>
</div>
<script>
  var link = document.querySelector('a');

  link.addEventListener('click', function() {
    event.currentTarget.innerHTML = 'Click event prevented using inline html'
    alert('Link Clicked');
  });


  function executeParent() {
    alert('Div Clicked');
  }
</script>

  1. Returning falsefrom a jQuery event handler.
  1. 从 jQuery 事件处理程序返回false

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
  <a href='http://stackoverflow.com'>Click here to visit stackoverflow.com</a>
</div>
<script>
  $('a').click(function(event) {
    alert('Link Clicked');
    $('a').text('Click event prevented using return FALSE');
    $('a').contents().unwrap();
    return false;
  });
  $('div').click(function(event) {
    alert('Div clicked');
  });
</script>

  1. Returning false from a regular DOM event handler.
  1. 从常规 DOM 事件处理程序返回 false。

<div onclick='executeParent()'>
  <a href='http://stackoverflow.com' onclick='executeChild()'>Click here to visit stackoverflow.com</a>
</div>
<script>
  function executeChild() {
    event.currentTarget.innerHTML = 'Click event prevented'
    alert('Link Clicked');
    return false
  }

  function executeParent() {
    alert('Div Clicked');
  }
</script>

Hope these examples are clear. Try executing all these examples in a html file to see how they work.

希望这些例子是清楚的。尝试在 html 文件中执行所有这些示例,看看它们是如何工作的。