简体   繁体   中英

My addEventListener does not work properly

The event listener works for a less than a second and then it doesn't work.

index.html file:

<!DOCTYPE html>
<html>
<head>
    <title>Javascript</title>
</head>
<body>

    <form id="my-form">
        <label id="lbl"></label>
        <button id="next">Next</button>
    </form>

    <script type="text/javascript" src="main.js"></script>
</body>
</html>

main.js file:

var myForm = document.getElementById("my-form");
var lbl = document.getElementById("lbl");
var nextBtn = document.getElementById("next");

nextBtn.addEventListener("click", displayDate);

function displayDate() {
    lbl.innerHTML = Date();
}

The date shows up for a less than a second, then it disappears instantly.

You have to cancel the form submit

 var myForm = document.getElementById("my-form"); var lbl = document.getElementById("lbl"); var nextBtn = document.getElementById("next"); nextBtn.addEventListener("click", displayDate); function displayDate() { lbl.innerHTML = Date(); } document.getElementById('my-form').onsubmit = function() { return false; }; 
 <!DOCTYPE html> <html> <head> <title>Javascript</title> </head> <body> <form id="my-form"> <label id="lbl"></label> <button id="next">Next</button> </form> </body> </html> 

You are clicking on a button element inside a form. The default button type is submit so:

  1. The button is clicked
  2. The click event is fired
  3. The JS handles the click event
  4. The form is submitted
  5. The browser loads a new page

… and the new page doesn't have the modifications you made with client-side code.


There are a couple of approaches you could take here.

The simplest is stop using a submit button .

Add type="button" to the <button> element.

You could also prevent the default behaviour of the button (to stop it submitting the form):

function displayDate(event) {
    event.preventDefault();
    lbl.innerHTML = Date();
}

The problem is, that you use a form. Upon clicking the Button you reload and so everything resets.

var myForm = document.getElementById("my-form");
var lbl = document.getElementById("lbl");
var nextBtn = document.getElementById("next");

nextBtn.addEventListener("click", displayDate);


myForm.addEventListener('submit', handleForm);

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


function displayDate() 
{
 lbl.innerHTML = Date();
}

This prevents the submit from reloading the page.

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