Event.defaultPrevented - Web APIs 编辑

The defaultPrevented read-only property of the Event interface returns a Boolean indicating whether or not the call to Event.preventDefault() canceled the event.

Note: You should use this instead of the non-standard, deprecated getPreventDefault() method (see bug 691151).

Syntax

var defaultWasPrevented = event.defaultPrevented;

Value

A Boolean, where true indicates that the default user agent action was prevented, and false indicates that it was not.

Example

This example logs attempts to visit links from two <a> elements. JavaScript is used to prevent the second link from working.

HTML

<p><a id="link1" href="#link1">Visit link 1</a></p>
<p><a id="link2" href="#link2">Try to visit link 2</a> (you can't)</p>
<p id="log"></p>

JavaScript

function stopLink(event) {
  event.preventDefault();
}

function logClick(event) {
  const log = document.getElementById('log');

  if (event.target.tagName === 'A') {
    if (event.defaultPrevented) {
      log.innerText = 'Sorry, but you cannot visit this link!\n' + log.innerText;
    }
    else {
      log.innerText = 'Visiting link...\n' + log.innerText;
    }
  }
}

const a = document.getElementById('link2');
a.addEventListener('click', stopLink);
document.addEventListener('click', logClick);

Result

Specifications

SpecificationStatusComment
DOM
The definition of 'Event.defaultPrevented()' in that specification.
Living Standard

Browser compatibility

BCD tables only load in the browser

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

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

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据

词条统计

浏览:141 次

字数:3608

最后编辑:6 年前

编辑次数:0 次

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