我正在尝试通过循环为我的主页上的每个按钮分配一个功能。 当单击前三个按钮中的每个按钮时,它应该将会话存储中的项目设置为true(Grass,Molluscs或Sweaters)。单击底部按钮时,它应显示已单击的所有其他按钮以及单词plants。
例如 如果我点击"向我发送有关Grass"的更多信息。 然后点击"您想了解更多信息" 最后一个按钮应该显示" Grass Plants" 如果我然后点击"向我发送有关软体动物的更多信息" 最后一个按钮应显示"软体动物草植物"
我的html和javascript文件 (我已经指出我相当确定的部分不能正常工作) (y [count] .id应该是" Grass"," Molluscs"或"毛衣") (infoChosen是页面上的第4个也是最后一个按钮)
window.onload = function() {
var y = document.getElementsByClassName("button");
for (count = 0; count < y.length; count++) {
if (y[count].id == "infoChosen") {
y[count].onclick = function() {
document.getElementById("infoChosen").innerHTML = "";
if (sessionStorage["Molluscs"] == "true") {
document.getElementById("infoChosen").innerHTML += "Green Molluscs\n";
}
if (sessionStorage["Sweaters"] == "true") {
document.getElementById("infoChosen").innerHTML += "Green Sweaters\n";
}
if (sessionStorage["Grass"] == "true") {
document.getElementById("infoChosen").innerHTML += "Grass\n";
}
if (sessionStorage["Plants"] == "true") {
document.getElementById("infoChosen").innerHTML += "Plants\n";
}
}
} else {
/////////////AREA OF THE CODE THATS NOT WORKING///////////////////////
y[count].onclick = (function(z) {
sessionStorage.setItem(z, "true");
})(y[count].id);
/////////////AREA OF THE CODE THATS NOT WORKING////////////////////////
}
sessionStorage.setItem(y[count].id, "false");
}
sessionStorage.setItem("Plants", "true");
}
&#13;
<div><button id="Grass" type="button" class="button">Send me more information about Grass</button></div>
<div><button id="Molluscs" type="button" class="button">Send me more information about Green Molluscs</button></div>
<div><button id="Sweaters" 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 id="displayInfo"></div>
<div><a href="otherPage.html">Other Page</a></div>
&#13;
otherPage.html只包含
<a href="example.html">Example</a>
答案 0 :(得分:2)
您没有通过此方式分配事件侦听器:
y[count].onclick = (function(z) {
sessionStorage.setItem(z, "true");
})(y[count].id);
因为 IIFE (即时调用的函数表达式)会立即评估其返回值。由于他们不返回任何内容,onclick
将为undefined
。您应该设置一个闭包,然后返回一个将分配给onclick
属性的函数,如下所示:
y[count].onclick = (function(z) {
return function() { // return a function reference to be assigned to the onclick
sessionStorage.setItem(z, "true");
};
})(y[count].id);