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

javascript - Why is the evt passed from an onSubmit undefined? - Stack Overflow

programmeradmin8浏览0评论

So I'm trying to get the onSubmit to be prevented in a form submission. I have 2 questions.

1) Where is the e parameter being passed in from?

2) Why is e undefined and therefore not correctly preventing the default action? The page refreshes each time which is the action that I'm trying to prevent

<html>
  <head>
  </head>
  <body>
    <form onSubmit={func}>
      <input type='text'/>
      <button type='submit'/>
    </form>
    <script>
      let func = (e) => {
        console.log('BEING CALLED')
        e.preventDefault()
      }
    </script>
  </body>
</html>

So I'm trying to get the onSubmit to be prevented in a form submission. I have 2 questions.

1) Where is the e parameter being passed in from?

2) Why is e undefined and therefore not correctly preventing the default action? The page refreshes each time which is the action that I'm trying to prevent

<html>
  <head>
  </head>
  <body>
    <form onSubmit={func}>
      <input type='text'/>
      <button type='submit'/>
    </form>
    <script>
      let func = (e) => {
        console.log('BEING CALLED')
        e.preventDefault()
      }
    </script>
  </body>
</html>
Share Improve this question asked Jan 25, 2017 at 7:00 DarkzuhDarkzuh 2494 silver badges11 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 9

Where is the e parameter being passed in from?

Nowhere

Why is e undefined and therefore not correctly preventing the default action?

Because the function isn't being called.


onSubmit={func}

Your JavaScript function:

  1. Starts a block (which has no practical effect)
  2. Mentions a function name (which has no effect because you didn't call it, bine it with an operator, or anything)
  3. Ends the block

All for a grand total of nothing.


The correct syntax for an onsubmit attribute would be:

onsubmit="func(event);"

… in which you actually call func and you pass it the argument you are trying to pass it. (Intrinsic event attributes get an argument called event automatically).


Binding events with HTML is considered bad practise, and they e with nasty gotchas. It is generally prefered to bind event handlers with JS.

document.querySelector("form")
        .addEventListener("submit", func);

Now func is the event handler itself, and it gets the event object as the first argument because that is what event handlers get.


Note that arrow functions are:

  1. Anonymous, which makes them less useful to work with in debuggers
  2. Capture the current value of this (which is usually unwele for event handlers since it stops you using this to get the element the handler was bound to).

Function declarations are generally preferable.

发布评论

评论列表(0)

  1. 暂无评论