Javascript 点击按钮在js中声明不';行不通

Javascript 点击按钮在js中声明不';行不通,javascript,dom-events,Javascript,Dom Events,我正在尝试在单击按钮后创建一个新的p标记,但单击后什么也没有发生: (function() { var xhttp = new XMLHttpRequest(); xhttp.onreadystatechange = function() { if (this.readyState == 4 && this.status == 403) { var heading = document.getElementById("head"); var

我正在尝试在单击
按钮
后创建一个新的
p
标记,但单击后什么也没有发生:

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

有人能帮我吗?

我假设document.getElementsByClassName(“theButton”)应该得到您的按钮,因为它使用相同的类

  • 这是不必要的,因为您已经有了对按钮的引用
  • 您的按钮(和段落)没有连接到DOM,因此getElementsByClassName将返回一个空结果
  • getElementsByCassName()返回HTMLCollection(列表),而不是单个元素。无法将侦听器函数添加到HTMLCollection
  • 该按钮仅在单击时添加到DOM中。但您只能在它被添加到DOM后单击它
  • 您也应该考虑使用AdvestTistListNER,因为您的侦听器不能以这种方式重写,并且可以添加多个侦听器。

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

    您创建了它,但从未将其插入DOM。或者我遗漏了什么?出于某种原因,将按钮附加到DOM的代码在click事件处理程序中。那没什么好处。将行
    标题.appendChild(按钮)
    移出该函数。明白!非常感谢。