event.stopPropagation 和 event.preventDefault 有什么区别?

发布于 2024-11-06 02:56:26 字数 277 浏览 5 评论 0 原文

他们似乎在做同样的事情......
一个是现代的,一个是旧的?或者不同的浏览器支持它们?

当我自己处理事件(没有框架)时,我总是检查两者并执行两者(如果存在)。 (我也返回 false,但我感觉它不适用于 node.addEventListener 附加的事件)。

那为什么两者都有呢?我应该继续检查两者吗?还是实际上有区别?

(我知道,有很多问题,但它们都是一样的=))

They seem to be doing the same thing...
Is one modern and one old? Or are they supported by different browsers?

When I handle events myself (without framework) I just always check for both and execute both if present. (I also return false, but I have the feeling that doesn't work with events attached with node.addEventListener).

So why both? Should I keep checking for both? Or is there actually a difference?

(I know, a lot of questions, but they're all sort of the same =))

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(9

时光无声 2024-11-13 02:56:26

stopPropagation 防止当前事件在捕获和冒泡阶段进一步传播。

preventDefault 阻止浏览器对该事件执行的默认操作。

示例

preventDefault

$("#but").click(function (event) {
  event.preventDefault()
})
$("#foo").click(function () {
  alert("parent click event fired!")
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="foo">
  <button id="but">button</button>
</div>

停止传播

$("#but").click(function (event) {
  event.stopPropagation()
})
$("#foo").click(function () {
  alert("parent click event fired!")
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="foo">
  <button id="but">button</button>
</div>

使用 stopPropagation 时,仅调用 button 的点击处理程序,而 div 的点击处理程序 永远不会触发。

就好像您使用 preventDefault 一样,只有浏览器的默认操作会停止,但 div 的点击处理程序仍然会触发。

以下是 MDN 中有关 DOM 事件属性和方法的一些文档:

对于 IE9 和 FF,您可以只使用 PreventDefault &停止传播。

要支持 IE8 及更低版本,请将 stopPropagation 替换为 cancelBubble,并将 preventDefault 替换为 returnValue

stopPropagation prevents further propagation of the current event in the capturing and bubbling phases.

preventDefault prevents the default action the browser makes on that event.

Examples

preventDefault

$("#but").click(function (event) {
  event.preventDefault()
})
$("#foo").click(function () {
  alert("parent click event fired!")
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="foo">
  <button id="but">button</button>
</div>

stopPropagation

$("#but").click(function (event) {
  event.stopPropagation()
})
$("#foo").click(function () {
  alert("parent click event fired!")
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="foo">
  <button id="but">button</button>
</div>

With stopPropagation, only the button's click handler is called while the div's click handler never fires.

Where as if you use preventDefault, only the browser's default action is stopped but the div's click handler still fires.

Below are some docs on the DOM event properties and methods from MDN:

For IE9 and FF you can just use preventDefault & stopPropagation.

To support IE8 and lower replace stopPropagation with cancelBubble and replace preventDefault with returnValue

左耳近心 2024-11-13 02:56:26

术语

来自 quirksmode.org

事件捕获

当您使用事件捕获时

<前> | |
---------------| |-----------------
|元素1 | | |
| ------------| |------------ |
| |元素2 \ / | |
| ---------------------------------- |
|事件捕捉 |
-----------------------------------

element1 的事件处理程序首先触发,element2 的事件处理程序最后触发。

事件冒泡

当您使用事件冒泡时

<前> / \
---------------| |-----------------
|元素1 | | |
| ------------| |------------ |
| |元素2 | | | |
| ---------------------------------- |
|活动冒泡 |
-----------------------------------

element2 的事件处理程序首先触发,element1 的事件处理程序最后触发。

W3C 事件模型中发生的任何事件都会首先被捕获,直到到达目标元素,然后再次冒泡

<前> | | /\
-----------------| |--| |-----------------
|元素1 | | | | |
| -------------| |--| |------------ |
| |元素2 \ / | | | |
| -------------------------------- |
| W3C 事件模型 |
------------------------------------------

来自 w3.org 的接口

,用于事件捕获

如果捕获EventListener希望阻止进一步处理
事件发生时,它可能会调用 stopPropagation 的方法
事件接口。这将阻止事件的进一步调度,
尽管在同一层次结构中注册了额外的 EventListeners
level 仍会收到该事件。一旦事件的 stopPropagation
方法已被调用,对该方法的进一步调用没有
额外的效果。如果不存在额外的捕获器并且
stopPropagation尚未被调用,该事件触发
目标本身上适当的EventListeners

对于事件冒泡

任何事件处理程序都可以选择通过以下方式阻止进一步的事件传播
调用 Event 接口的 stopPropagation 方法。如果有的话
EventListener 调用此方法,所有附加的 EventListeners
当前的 EventTarget 将被触发,但冒泡将停止
等级。只需调用一次 stopPropagation 即可防止进一步发生
冒泡。

对于活动取消

通过调用EventpreventDefault来完成取消
方法。如果一个或多个 EventListeners 在执行期间调用 preventDefault
事件流的任何阶段默认操作都将被取消。

示例

在以下示例中,单击 Web 浏览器中的超链接将触发事件流(执行事件侦听器)和事件目标的默认操作(打开新选项卡)。

HTML:

<div id="a">
  <a id="b" href="http://www.google.com/" target="_blank">Google</a>
</div>
<p id="c"></p>

JavaScript:

var el = document.getElementById("c");

function capturingOnClick1(ev) {
    el.innerHTML += "DIV event capture<br>";
}

function capturingOnClick2(ev) {
    el.innerHTML += "A event capture<br>";
}

function bubblingOnClick1(ev) {
    el.innerHTML += "DIV event bubbling<br>";
}

function bubblingOnClick2(ev) {
    el.innerHTML += "A event bubbling<br>";
}

// The 3rd parameter useCapture makes the event listener capturing (false by default)
document.getElementById("a").addEventListener("click", capturingOnClick1, true);
document.getElementById("b").addEventListener("click", capturingOnClick2, true);
document.getElementById("a").addEventListener("click", bubblingOnClick1, false);
document.getElementById("b").addEventListener("click", bubblingOnClick2, false);

示例 1:输出结果

DIV event capture
A event capture
A event bubbling
DIV event bubbling

示例 2:将 stopPropagation() 添加到函数

function capturingOnClick1(ev) {
    el.innerHTML += "DIV event capture<br>";
    ev.stopPropagation();
}

结果的输出中

DIV event capture

事件侦听器阻止了事件。但是,它并没有阻止默认操作(打开新选项卡)。

示例 3:向函数添加 stopPropagation()

function capturingOnClick2(ev) {
    el.innerHTML += "A event capture<br>";
    ev.stopPropagation();
}

或函数

function bubblingOnClick2(ev) {
    el.innerHTML += "A event bubbling<br>";
    ev.stopPropagation();
}

结果输出

DIV event capture
A event capture
A event bubbling

这是因为两个事件侦听器都注册在同一事件目标上。事件侦听器阻止事件进一步向上传播。但是,它们并没有阻止默认操作(打开新选项卡)。

示例 4:将 preventDefault() 添加到任何函数,例如

function capturingOnClick1(ev) {
    el.innerHTML += "DIV event capture<br>";
    ev.preventDefault();
}

防止打开新标签。

Terminology

From quirksmode.org:

Event capturing

When you use event capturing

               | |
---------------| |-----------------
| element1     | |                |
|   -----------| |-----------     |
|   |element2  \ /          |     |
|   -------------------------     |
|        Event CAPTURING          |
-----------------------------------

the event handler of element1 fires first, the event handler of element2 fires last.

Event bubbling

When you use event bubbling

               / \
---------------| |-----------------
| element1     | |                |
|   -----------| |-----------     |
|   |element2  | |          |     |
|   -------------------------     |
|        Event BUBBLING           |
-----------------------------------

the event handler of element2 fires first, the event handler of element1 fires last.

Any event taking place in the W3C event model is first captured until it reaches the target element and then bubbles up again.

                 | |  / \
-----------------| |--| |-----------------
| element1       | |  | |                |
|   -------------| |--| |-----------     |
|   |element2    \ /  | |          |     |
|   --------------------------------     |
|        W3C event model                 |
------------------------------------------

Interface

From w3.org, for event capture:

If the capturing EventListener wishes to prevent further processing of
the event from occurring it may call the stopPropagation method of the
Event interface. This will prevent further dispatch of the event,
although additional EventListeners registered at the same hierarchy
level will still receive the event. Once an event's stopPropagation
method has been called, further calls to that method have no
additional effect. If no additional capturers exist and
stopPropagation has not been called, the event triggers the
appropriate EventListeners on the target itself.

For event bubbling:

Any event handler may choose to prevent further event propagation by
calling the stopPropagation method of the Event interface. If any
EventListener calls this method, all additional EventListeners on the
current EventTarget will be triggered but bubbling will cease at that
level. Only one call to stopPropagation is required to prevent further
bubbling.

For event cancelation:

Cancelation is accomplished by calling the Event's preventDefault
method. If one or more EventListeners call preventDefault during
any phase of event flow the default action will be canceled.

Examples

In the following examples, a click on the hyperlink in the web browser triggers the event's flow (the event listeners are executed) and the event target's default action (a new tab is opened).

HTML:

<div id="a">
  <a id="b" href="http://www.google.com/" target="_blank">Google</a>
</div>
<p id="c"></p>

JavaScript:

var el = document.getElementById("c");

function capturingOnClick1(ev) {
    el.innerHTML += "DIV event capture<br>";
}

function capturingOnClick2(ev) {
    el.innerHTML += "A event capture<br>";
}

function bubblingOnClick1(ev) {
    el.innerHTML += "DIV event bubbling<br>";
}

function bubblingOnClick2(ev) {
    el.innerHTML += "A event bubbling<br>";
}

// The 3rd parameter useCapture makes the event listener capturing (false by default)
document.getElementById("a").addEventListener("click", capturingOnClick1, true);
document.getElementById("b").addEventListener("click", capturingOnClick2, true);
document.getElementById("a").addEventListener("click", bubblingOnClick1, false);
document.getElementById("b").addEventListener("click", bubblingOnClick2, false);

Example 1: it results in the output

DIV event capture
A event capture
A event bubbling
DIV event bubbling

Example 2: adding stopPropagation() to the function

function capturingOnClick1(ev) {
    el.innerHTML += "DIV event capture<br>";
    ev.stopPropagation();
}

results in the output

DIV event capture

The event listener prevented further downward and upward propagation of the event. However it did not prevent the default action (a new tab opening).

Example 3: adding stopPropagation() to the function

function capturingOnClick2(ev) {
    el.innerHTML += "A event capture<br>";
    ev.stopPropagation();
}

or the function

function bubblingOnClick2(ev) {
    el.innerHTML += "A event bubbling<br>";
    ev.stopPropagation();
}

results in the output

DIV event capture
A event capture
A event bubbling

This is because both event listeners are registered on the same event target. The event listeners prevented further upward propagation of the event. However they did not prevent the default action (a new tab opening).

Example 4: adding preventDefault() to any function, for instance

function capturingOnClick1(ev) {
    el.innerHTML += "DIV event capture<br>";
    ev.preventDefault();
}

prevents a new tab from opening.

禾厶谷欠 2024-11-13 02:56:26

return false;


return false; 当您调用它时,它会执行 3 件不同的事情:

  1. event.preventDefault() – 它会停止浏览器的默认行为。
  2. event.stopPropagation() – 它阻止事件在 DOM 中传播(或“冒泡”)。
  3. 停止回调执行并在调用时立即返回。

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

preventDefault();


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

何时使用它们?


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

示例:


让我们尝试通过示例来理解:

我们将看到纯 JAVASCRIPT 示例

示例 1:

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

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

运行上面的代码你会看到超链接'点击这里访问
stackoverflow.com'
现在,如果您首先单击该链接,您将获得
javascript 警报 已点击链接 接下来您将收到 javascript
警报div Clicked,您将立即被重定向到
stackoverflow.com。

示例2:

<div onclick='executeParent()'>
  <a href='https://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>

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

示例3:

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

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

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

示例 4:

<div onclick='executeParent()'>
  <a href='https://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>

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

示例5:

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

情况:

  1. 从内联事件处理程序返回 false 会阻止浏览器导航到链接地址,但不会阻止事件通过 DOM 传播。
  2. 从 jQuery 事件处理程序返回 false 会阻止浏览器导航到链接地址,并阻止事件通过 DOM 传播。
  3. 从常规 DOM 事件处理程序返回 false 绝对不会执行任何操作。

将看到所有三个示例。

  1. 内联返回 false。
<div onclick='executeParent()'>
  <a href='https://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. 从 jQuery 事件处理程序返回 false
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
  <a href='https://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. 从常规 DOM 事件处理程序返回 false。
<div onclick='executeParent()'>
  <a href='https://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>

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

return false;


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

  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.

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

preventDefault();


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

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().

Examples:


Let’s try to understand with examples:

We will see pure JAVASCRIPT example

Example 1:

<div onclick='executeParent()'>
  <a href='https://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 Clicked Next you will get the javascript
alert div Clicked and immediately you will be redirected to
stackoverflow.com.

Example 2:

<div onclick='executeParent()'>
  <a href='https://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 Clicked Next you will get the javascript
alert div Clicked 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 due > to event.preventDefault() method we used to prevent the default click
action to be triggered.

Example 3:

<div onclick='executeParent()'>
  <a href='https://stackoverflow.com' onclick='executeChild()'>Click here to visit stackoverflow.com</a>
</div>
<script>
  function executeChild() {
    event.stopPropagation();
    event.currentTarget.innerHTML = 'Click event prevented'
    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 Clicked
this 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.

Example 4:

<div onclick='executeParent()'>
  <a href='https://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.

Example 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.

cases:

  1. Returning false from 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 false from 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 false from a regular DOM event handler does absolutely nothing.

Will see all three example.

  1. Inline return false.

<div onclick='executeParent()'>
  <a href='https://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 false from a jQuery event handler.

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
  <a href='https://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.

<div onclick='executeParent()'>
  <a href='https://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.

鲜血染红嫁衣 2024-11-13 02:56:26

的引用。

这是此处 Event.preventDefault

PreventDefault 方法可防止事件执行其默认功能。例如,您可以在 A 元素上使用 PreventDefault 来阻止单击该元素离开当前页面:

//clicking the link will *not* allow the user to leave the page 
myChildElement.onclick = function(e) { 
    e.preventDefault(); 
    console.log('brick me!'); 
};

//clicking the parent node will run the following console statement because event propagation occurs
logo.parentNode.onclick = function(e) { 
    console.log('you bricked my child!'); 
};

当该元素的默认功能被阻塞时,该事件会继续在 DOM 中冒泡。

Event.stopPropagation

第二种方法 stopPropagation 允许事件的默认功能发生,但阻止事件传播:

//clicking the element will allow the default action to occur but propagation will be stopped...
myChildElement.onclick = function(e) { 
    e.stopPropagation();
    console.log('prop stop! no bubbles!'); 
};

//since propagation was stopped by the child element's onClick, this message will never be seen!
myChildElement.parentNode.onclick = function(e) { 
    console.log('you will never see this message!'); 
};

stopPropagation 有效地阻止父元素了解其子元素上的给定事件。

虽然简单的 stop 方法可以让我们快速处理事件,但它
重要的是要考虑一下你到底想要发生什么
冒泡。我敢打赌,开发人员真正想要的就是 PreventDefault
90%的时间!错误地“停止”事件可能会导致您
无数的麻烦;您的插件可能无法工作,并且您的
第三方插件可能会变砖。或者更糟糕的是——你的代码
破坏网站上的其他功能。

This is the quote from here

Event.preventDefault

The preventDefault method prevents an event from carrying out its default functionality. For example, you would use preventDefault on an A element to stop clicking that element from leaving the current page:

//clicking the link will *not* allow the user to leave the page 
myChildElement.onclick = function(e) { 
    e.preventDefault(); 
    console.log('brick me!'); 
};

//clicking the parent node will run the following console statement because event propagation occurs
logo.parentNode.onclick = function(e) { 
    console.log('you bricked my child!'); 
};

While the element's default functionality is bricked, the event continues to bubble up the DOM.

Event.stopPropagation

The second method, stopPropagation, allows the event's default functionality to happen but prevents the event from propagating:

//clicking the element will allow the default action to occur but propagation will be stopped...
myChildElement.onclick = function(e) { 
    e.stopPropagation();
    console.log('prop stop! no bubbles!'); 
};

//since propagation was stopped by the child element's onClick, this message will never be seen!
myChildElement.parentNode.onclick = function(e) { 
    console.log('you will never see this message!'); 
};

stopPropagation effectively stops parent elements from knowing about a given event on its child.

While a simple stop method allows us to quickly handle events, it's
important to think about what exactly you want to happen with
bubbling. I'd bet that all a developer really wants is preventDefault
90% of the time! Incorrectly "stopping" an event could cause you
numerous troubles down the line; your plugins may not work and your
third party plugins could be bricked. Or worse yet -- your code
breaks other functionality on a site.

緦唸λ蓇 2024-11-13 02:56:26

event.preventDefault()
阻止浏览器的默认行为(例如打开链接),但不会阻止事件在 DOM 中冒泡。

event.stopPropagation()
防止事件在 DOM 中冒泡,但不会停止浏览器的默认行为。

return false;
通常出现在 jQuery 代码中,它阻止浏览器的默认行为,阻止事件冒泡
DOM,并立即从任何回调返回。

看看这个 真的很好& 4 分钟轻松阅读,其中包含上述文章中的示例。

event.preventDefault()
Prevents the browsers default behaviour (such as opening a link), but does not stop the event from bubbling up the DOM.

event.stopPropagation()
Prevents the event from bubbling up the DOM, but does not stop the browsers default behaviour.

return false;
Usually seen in jQuery code, it prevents the browsers default behaviour, prevents the event from bubbling up the
DOM, and immediately Returns from any callback.

Check out this really nice & easy 4 min read with examples from where the above piece was taken.

还在原地等你 2024-11-13 02:56:26

event.preventDefault(); 阻止元素的默认操作发生。

event.stopPropagation(); 防止事件在 DOM 树中向上冒泡,从而防止任何父处理程序收到该事件的通知。

例如,如果在 DIVFORM 内部附加了 click 方法的链接也附加了 click 方法,则它将阻止 DIV< /code> 或 FORM 点击方法触发。

event.preventDefault(); Stops the default action of an element from happening.

event.stopPropagation(); Prevents the event from bubbling up the DOM tree, preventing any parent handlers from being notified of the event.

For example, if there is a link with a click method attached inside of a DIV or FORM that also has a click method attached, it will prevent the DIV or FORM click method from firing.

黑寡妇 2024-11-13 02:56:26

Event.preventDefault - 停止浏览器默认行为。现在什么是浏览器默认行为。假设您有一个锚标记,它有一个 href 属性,并且该锚标记嵌套在一个有单击事件的 div 标记内。锚标记的默认行为是当单击锚标记时它应该导航,但 event.preventDefault 的作用是在这种情况下停止导航。但它永远不会停止事件的冒泡或事件的升级,即

<div class="container">
 <a href="#" class="element">Click Me!</a>
</div>

$('.container').on('click', function(e) {
 console.log('container was clicked');
});

$('.element').on('click', function(e) {
  e.preventDefault(); // Now link won't go anywhere
  console.log('element was clicked');
});

结果将是

“元素被单击”

“容器被单击”

现在 event.StopPropation 它停止事件的冒泡或事件升级。现在,上面的示例

$('.container').on('click', function(e) {
  console.log('container was clicked');
});

$('.element').on('click', function(e) {
  e.preventDefault(); // Now link won't go anywhere
  e.stopPropagation(); // Now the event won't bubble up
 console.log('element was clicked');
});

结果将是

“元素被单击”

有关更多信息,请参阅此链接
https://codeplanet.io/preventdefault-vs-stoppropagation-vs-stopimmediatepropagation/

Event.preventDefault- stops browser default behaviour. Now comes what is browser default behaviour. Assume you have a anchor tag and it has got a href attribute and this anchor tag is nested inside a div tag which has got a click event. Default behaviour of anchor tag is when clicked on the anchor tag it should navigate, but what event.preventDefault does is it stops the navigation in this case. But it never stops the bubbling of event or escalation of event i.e

<div class="container">
 <a href="#" class="element">Click Me!</a>
</div>

$('.container').on('click', function(e) {
 console.log('container was clicked');
});

$('.element').on('click', function(e) {
  e.preventDefault(); // Now link won't go anywhere
  console.log('element was clicked');
});

The result will be

"element was clicked"

"container was clicked"

Now event.StopPropation it stops bubbling of event or escalation of event. Now with above example

$('.container').on('click', function(e) {
  console.log('container was clicked');
});

$('.element').on('click', function(e) {
  e.preventDefault(); // Now link won't go anywhere
  e.stopPropagation(); // Now the event won't bubble up
 console.log('element was clicked');
});

Result will be

"element was clicked"

For more info refer this link
https://codeplanet.io/preventdefault-vs-stoppropagation-vs-stopimmediatepropagation/

夏雨凉 2024-11-13 02:56:26

让我们比较一下 preventDefaultstopPropagation

所有这些都可以在事件处理函数中使用。

event.preventDefault() 防止给定元素的默认浏览器行为。在 form 元素中,它阻止表单提交,对于 href 元素,它阻止导航。

event.stopPropagation() 停止事件在 DOM 树中冒泡或向上传播。

然而,

return false 是 PreventDefault() 和 stopPropagation() 的组合。

Lets compare preventDefault and stopPropagation

All of these can be used in event handler functions.

event.preventDefault() prevents the default browser behavior for a given element. In form element it prevents form submitting and for href element it prevents navigating.

event.stopPropagation() stops an event from bubbling or propagating up the DOM tree.

Whereas,

return false is a combination of both preventDefault() and stopPropagation().

停顿的约定 2024-11-13 02:56:26
$("#but").click(function(event){
console.log("hello");
  event.preventDefault();
 });


$("#foo").click(function(){
 alert("parent click event fired !");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="foo">
  <button id="but">button</button>
</div>

$("#but").click(function(event){
console.log("hello");
  event.preventDefault();
 });


$("#foo").click(function(){
 alert("parent click event fired !");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="foo">
  <button id="but">button</button>
</div>

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文