最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Does location of `e.preventDefault()` matter? - Stack Overflow

programmeradmin3浏览0评论

I use preventDefault() in my jquery functions to prevent submit buttons from submitting the normal way. Does the location of preventDefault() matter. Does it have to come first or can be last thing in the function?

I use preventDefault() in my jquery functions to prevent submit buttons from submitting the normal way. Does the location of preventDefault() matter. Does it have to come first or can be last thing in the function?

Share Improve this question edited Dec 19, 2023 at 16:00 Artur INTECH 7,2863 gold badges48 silver badges39 bronze badges asked Dec 18, 2010 at 6:37 samisami 7,6458 gold badges36 silver badges38 bronze badges
Add a comment  | 

4 Answers 4

Reset to default 12

No, it doesn't matter: https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault

This is different from returning false, since when you returns, everything else in the function are abandoned.

As said in the MDC link given above:

Calling preventDefault during any stage of event flow cancels the event, meaning that any default action normally taken by the implementation as a result of the event will not occur.

It doesn't matter, but I like to put it first. The intended behavior is clear on a quick scan of the code when it's right up top.

December 2023 update:

It depends on the nature of the default action implemented by browser vendors. It some cases a failure of preventing the default action from firing may complicate debugging and/or make user UI poorer.


For example, special caution should be taken when using preventDefault() in conjunction with the form's submit event.

Imagine that we want to submit a form using XMLHttpRequest instead of letting the browser to take a user to a new URL (the default action).

When preventDefault() comes last, as in the following example, and our custom logic throws an exception, the browser will print an error message in the console and immediately redirects a user to the URL specified in the form's action. This leads to a hard-to-debug error, since you will not notice an error (unless Preserve log browser setting is enabled) and the server response will be printed as is by the browser (JSON, for example):

document.querySelector('form').addEventListener('submit', (event) => {
    someRequestThatCanThrowAnException.make();
    event.preventDefault();
});

Whereas in the example below preventDefault() comes first so we prevent the default action from happening no matter whether our custom logic fails or not:

document.querySelector('form').addEventListener('submit', (event) => {
    event.preventDefault();

    someRequestThatCanThrowAnException.make();
    throw new Error('another error');
});

Therefore, it might be a good practice to always put preventDefault() as close to the beginning of the callback function as possible by default, in order to avoid spending hours on debugging when placed at the end.

It only matters if somewhere in the code ran from your handler something checks whether the event has been canceled or not:

addEventListener("something", (evt) => {
  doSomethingWithEvent(evt, "before");
  evt.preventDefault();
  doSomethingWithEvent(evt, "after");
});

function doSomethingWithEvent(evt, pos) {
  if (!evt.defaultPrevented) {
    console.log("I do something", pos);
  }
  else {
    console.log("I do not do something", pos);
  }
}

dispatchEvent(new Event("something", { cancelable: true }));

If you're sure nothing from your handler will check the defaultPrevented property, then it's the same, even if some other code checks it outside of the handler.

发布评论

评论列表(0)

  1. 暂无评论