繁体   English   中英

将参数传递给嵌入式JavaScript函数

[英]Passing parameters to an inline javascript function

我试图通过循环将功能分配给主页上的每个按钮。 单击前三个按钮中的每个按钮时,应将会话存储中的一项设置为true(草,软体动物或毛衣)。 单击底部按钮时,它应显示所有其他被单击的按钮以及词植物。

例如,如果我单击“向我发送有关草的更多信息”,然后单击“你想获得的更多信息”,则最后一个按钮应显示“草类植物”。如果我单击“向我发送有关软体动物的更多信息”,则最后一个按钮应然后显示“软体动物草类植物”

我的html和javascript文件(我已经确定相当确定的部分无法正常工作)(y [count] .id应该是单词“ Grass”,“ Molluscs”或“ Sweaters”)(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"); } 
  <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>  

您不是通过以下方式分配事件侦听器的:

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);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM