简体   繁体   中英

Button on click declared in js doesn't work

I am trying to create a new p tag after the button is clicked yet nothing happens after it's clicked:

(function() {
  var xhttp = new XMLHttpRequest();
  xhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 403) {
      var heading = document.getElementById("head");
      var para = document.createElement("P");
      para.innerHTML = "Accept the T&Cs to Continue";
      var button = document.createElement("BUTTON"); // button created here
      button.classList.add("theButton");
      var theButton = document.getElementsByClassName("theButton");
      theButton.onclick = function() { // button doesn't work onclick
        var newP = document.createElement("P");
        newP.innerHTML = "DONE";
        heading.appendChild(newP);
        heading.appendChild(para);
        heading.appendChild(button);
      };
    }
  };
  xhttp.open("GET", "/content.ajax", true);
  xhttp.send();
})();

Can someone help me with this?

I´m assuming that document.getElementsByClassName("theButton") should get your button, because it uses the same class.

  1. That´s unnecessary because you already have a reference to your button.
  2. Your button (and para) did not get attached to the DOM, so getElementsByClassName would return an empty result.
  3. document.getElementsByClassName() returns a HTMLCollection (a list), not a single element. You can´t add a listener function to a HTMLCollection.
  4. The button only gets added to the DOM when it is clicked. But you can only click it after it got added to the DOM.

Also you should consider using addEventListener because your listener can´t be overwritten that way and you can add multiple listeners.

(function () {
    var xhttp = new XMLHttpRequest();
    xhttp.onreadystatechange = function() {
        if(this.readyState ==4 && this.status == 403){
            var heading = document.getElementById("head");
            var para = document.createElement("P");
            para.innerHTML = "Accept the T&Cs to Continue";

            var button = document.createElement("BUTTON"); // button created here
            button.classList.add("theButton");
            button.addEventListener("click", function() {
                var newP = document.createElement("P");
                newP.innerHTML = "DONE";
                heading.appendChild(newP);
            });

            heading.appendChild(para);
            heading.appendChild(button);
        }
    };
    xhttp.open("GET","/content.ajax",true);
    xhttp.send();
})();

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