简体   繁体   中英

JavaScript, post, button will not give server response until the second click

I have a script that is scanning a page for all buttons and logging the click of each into the database. Unfortunately the button data will not submit until the second click am I using the addEventListener and removeEvent listener in the correct location?

var trkButtons = document.getElementsByTagName('input');

for (var i = 0; i < trkButtons.length; ++i) {

    //submit button
    if (trkButtons[i].getAttribute("type") == "submit") {
        trkButtons[i].addEventListener("click", addBtnClickListener, false);
    }

    //image button
    if (trkButtons[i].getAttribute("type") == "image") {
        trkButtons[i].addEventListener("click", addBtnClickListener, false);
    }

    //file upload
    if (trkButtons[i].getAttribute("type") == "file") {
        trkButtons[i].addEventListener("click", addBtnClickListener, false);
    }
    else { }
}

function addBtnClickListener(e) {
    e.preventDefault();

    this.click();
    this.removeEventListener('click', addBtnClickListener, false);

    var eventType = "button.click";
    var ctrBtnText = this.value;
    track(this, eventType, '', '', ctrBtnText, '', '', '');

}

Okay, so here is what your addBtnClickListener function does:

  1. Prevents default action to run (form submission, file upload window opening)
  2. Run this function one more time
  3. Remove this event listener from the clicked element
  4. Log stuff

Form submission works the second time because first time, at step 3 you remove this event handler which actually prevents form submission.
If you don't wanna prevent default behavior like form submitting, file upload dialog opening, etc. then you should not use e.preventDefault() .

Possible solution:

function addBtnClickListener(e) {
    // the code below will be executed, before the form is submitted
    // no need for other action if this is all we do
    var eventType = "button.click";
    var ctrBtnText = this.value;
    track(this, eventType, '', '', ctrBtnText, '', '', '');
}

Reason to use preventDefault:

function validateForm(e) {
    var data = document.getElementById('someData').value;
    if (isValid(data) === false) {
        e.preventDefault();
        // ask user to correct invalid data here
    }
}

Note: you can submit forms manually with this.form.submit() but this is usually not needed as the default action does this for us.

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