将函数分配给javascript按钮数组
当我点击这些按钮时,我希望sessionStorage中的一个项目被指定为true,这表示按下的按钮。当点击第四个按钮时,我看到它显示选择了哪些信息来了解更多信息 现在我的按钮没有返回任何东西,我不知道如何循环并为每个按钮分配一个函数将函数分配给javascript按钮数组,javascript,html,loops,Javascript,Html,Loops,当我点击这些按钮时,我希望sessionStorage中的一个项目被指定为true,这表示按下的按钮。当点击第四个按钮时,我看到它显示选择了哪些信息来了解更多信息 现在我的按钮没有返回任何东西,我不知道如何循环并为每个按钮分配一个函数 //simple html to print four buttons. <!DOCTYPE html> <html> <head> <title>Green Things</title
//simple html to print four buttons.
<!DOCTYPE html>
<html>
<head>
<title>Green Things</title>
<script type="text/javascript" src="example.js"></script>
</head>
<body>
<div><button id="moreAboutGrass" type="button" class="button">Send me more information about Grass</button></div>
<div><button id="moreAboutMolluscs" type="button" class="button">Send me more information about Green Molluscs</button></div>
<div><button id="moreAboutSweaters" type="button" class="button">Send me more information about Green Sweaters</button></div>
<div> <button id="infoChosen" type="button" class="button">Things you want more information about </button></div>
<div><output id = "output"></output></div>
</body>
</html>
window.onload = function() {
//getting an array of all the buttons
var y = document.getElementsByClassName("button");
//looping through all the buttons
for(count = 0; count < y.length; count++){
//Assigning an operation to the button
document.getElementById(y[count].id).onclick = function(count) {
//Assigning a variable to be the id name of button passed into this function
z = y[arguments[i]].id;
//If the button is the fourth button
if ( z == "infoChosen" ){
//Add in the things which were selected
document.getElementById("output").innerHTML = "";
if (sessionStorage["moreAboutMolluscs"] == "true"){
document.getElementById("output").innerHTML += "Green Molluscs\n";
}
if (sessionStorage["moreAboutSweaters"] == "true"){
document.getElementById("output").innerHTML += "Green Sweaters\n";
}
if (sessionStorage["moreAboutGrass"] == "true"){
document.getElementById("output").innerHTML += "Grass\n";
}
}else{
//if the button was on of the first 3 just set a variable to true so it can be printed later
sessionStorage.setItem(z, "true");
}
}
}
如果单击第一个和第三个按钮,然后单击第四个按钮,则应显示输出
Green Molluscs
Green Molluscs Green Sweaters
我需要做一个循环在这种情况下,我会做不同的事情。 在我看来,最好的选择是为每个按钮创建一个函数,就像这样,单击意味着该函数会改变一个变量的真假。当您单击第4个按钮时,最好也使用switch语句来获得正确的输出 我还没有那么丰富的编码经验,所以这可能不是最有效的方法,但我希望这对您有所帮助。试试这个 绿色事物 window.onload=函数{ //获取所有按钮的数组 var y=document.getElementsByClassNamebutton; //在所有按钮之间循环 forcount=0;count