简体   繁体   中英

Using submit button with e.preventDefault() vs a regular button

I'm following an MDN article on client-storage ( https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Client-side_web_APIs/Client-side_storage ), and I ran across a snippet of code that I had a question about. The example is supposed to show how to use the Web Storage API for simple data persistence, and so it has us enter a name in a form field in order to save that data and render a personalized greeting that persists across sessions. In order to accept user input, it uses an <input type="submit"> button and then attaches an event listener on it with form.addEventListener('submit', function(e) { e.preventDefault(); }); I've noticed this pattern in quite a few of the articles, and so my question is why should we use a submit button and prevent default submit behavior over just creating a regular button? Are there advantages to each? To be clear, I'm not asking why one should use <input type="submit"> over <button> in general ; I'm wondering why <input type="submit"> is used in a situation where submitting is not desired when we have <button> or <input type="button"> .

form.addEventListener('submit', function(e) { e.preventDefault(); });

is not binding to a button, but to form submission. Users can submit a form by hitting enter for instance. On mobile devices keyboards might offer similar function. People using assistive technology might have other options too.

This is important because you express intent to the browser.

It can be quite confusing having a form where only the button itself works, but other means you might be used to do not work.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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