【发布时间】:2017-02-21 13:26:44
【问题描述】:
我正在尝试通过循环为主页上的每个按钮分配一个功能。 当单击前三个按钮中的每一个时,它应该将会话存储中的一个项目设置为 true(草、软体动物或毛衣)。单击底部按钮时,应显示所有其他被单击的按钮以及植物一词。
例如 如果我单击“向我发送有关草的更多信息” 然后点击“您想了解更多信息的事情” 最后一个按钮应显示“草本植物” 如果我然后单击“向我发送有关软体动物的更多信息” 最后一个按钮应该显示“软体动物草植物”
我的 html 和 javascript 文件 (我已经指出我相当肯定的部分不能正常工作) (y[count].id 应该是“草”、“软体动物”或“毛衣”这个词) (infoChosen 是页面上的第四个也是最后一个按钮)
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");
}
<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>
otherPage.html 只包含
<a href="example.html">Example</a>
【问题讨论】:
标签: javascript html onclick session-storage