我有这个隐藏一些按钮并创建另一个按钮的功能,当我点击创建的按钮时,它应该再次显示那些之前被隐藏的按钮,但它并没有真正起作用。
function hideButtons(){
var buttons=document.getElementsByTagName("input");
for(var i=0;i<buttons.length;i++) {
if(buttons[i].type=="button"){
buttons[i].style.display="none";}
}
var back=document.createElement("input");
back.setAttribute("type", "button");
back.setAttribute("value","BACK");
back.setAttribute("id","btnBack");
back.onclick=showButtons();
document.body.appendChild(back);
}
function showButtons(){
var buttons=document.getElementsByTagName("input");
for(var i=0;i<buttons.length;i++) {
buttons[i].style.display="initial";
}
}
答案 0 :(得分:1)
附加事件侦听器时,不得调用侦听器函数:
function hideButtons () {
var buttons = document.querySelectorAll("input[type=button]");
for (var i = 0; i < buttons.length; i++) {
buttons[i].style.display = "none";
if (buttons[i].getAttribute("id") === "btnBack") {
// remove the id from the current "back" button
buttons[i].removeAttribute("id");
}
}
var back = document.createElement("input");
back.setAttribute("type", "button");
back.setAttribute("value","BACK");
back.setAttribute("id","btnBack");
back.onclick = showButtons; // important!
document.body.appendChild(back);
}
function showButtons () {
var buttons = document.querySelectorAll("input[type=button]");
for (var i = 0; i < buttons.length; i++) {
buttons[i].style.display = "initial";
}
}
答案 1 :(得分:0)
就像PeterMader所说,问题是你在事件监听器中调用showButtons()
函数。你想像Peter建议的那样调用对函数的引用,或者另一种方法是将showButtons()
包装在函数中。
function hideButtons() {
var buttons = document.getElementsByTagName("input");
for (var i = 0; i < buttons.length; i++) {
if (buttons[i].type == "button") {
buttons[i].style.display = "none";
}
}
var back = document.createElement("input");
back.setAttribute("type", "button");
back.setAttribute("value", "BACK");
back.setAttribute("id", "btnBack");
back.onclick = function() {
showButtons();
}
document.body.appendChild(back);
}
function showButtons() {
var buttons = document.getElementsByTagName("input");
for (var i = 0; i < buttons.length; i++) {
buttons[i].style.display = "initial";
}
}
hideButtons();
<input type="button">
<input type="button">
<input type="button">
<input>