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”)应该得到您的按钮,因为它使用相同的类
您也应该考虑使用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(按钮)
移出该函数。明白!非常感谢。