简体   繁体   中英

Why EventListener reloads the page and onclick does not?

I have been having problems lately with a page reloading during form submission. I finally found out that the page reloads when I submit the form with EventListener, but it doesn't reload with onclick form submission. The code below is how I tested that. Can someone please explain to me why?

<html>
  <head>
    <title>Reload Page Test</title>
    <script>
      document.addEventListener("DOMContentLoaded", function () {

        document.querySelector("#asubmit").addEventListener("click", test);

        document.querySelector("#bsubmit").onclick = test;
        
        function test(){
          const name = document.getElementById("name").value;
          const age = document.getElementById("num").value;
          document.getElementById(
            "result"
          ).innerHTML = `${name} is ${age}years old.`;
          return false;
        };

      });
    </script>
  </head>
  <body>

    <div>
      <form>
        <input type="text" id="name" />
        <input type="number" id="num" />
        <input type="submit" id="asubmit" value="Event Listener Submit"/>
        <input type="submit" id="bsubmit" value="On Click Submit">
      </form>`enter code here`
    </div>
    <div id="result"></div>

  </body>
</html>

Returning false from an onclick function will prevent the default behaviour.

The return value of an event listener callback is meaningless.

Use event.preventDefault() instead.

function test(event) {
    // ...
    event.preventDefault();
}

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