Кнопка при нажатии, объявленная в js, не работает - PullRequest
0 голосов
/ 31 марта 2020

Я пытаюсь создать новый тег p после нажатия button, но после нажатия ничего не происходит:

(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();
})();

Может кто-нибудь помочь мне с этим?

1 Ответ

1 голос
/ 31 марта 2020

Я предполагаю, что document.getElementsByClassName ("theButton") должен получить вашу кнопку, потому что он использует тот же класс.

  1. Это не нужно, потому что у вас уже есть ссылка на вашу кнопку .
  2. Ваша кнопка (и пункт) не была прикреплена к DOM, поэтому getElementsByClassName вернет пустой результат.
  3. document.getElementsByClassName () возвращает HTMLCollection (список), а не a один элемент Вы не можете добавить функцию слушателя в HTMLCollection.
  4. Кнопка добавляется в DOM только при нажатии. Но вы можете щелкнуть по нему только после того, как он был добавлен в DOM.

Также вы должны рассмотреть возможность использования addEventListener, потому что ваш слушатель не может быть перезаписан таким образом, и вы можете добавить несколько слушателей.

(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();
})();
...