繁体   English   中英

在使用 Js 的 Click 事件之后,从 forEach 循环中获取特定值

[英]Getting Particular Value from the forEach loop ,after Click Event using Js

我正在尝试从 Object 数组(存储在形成树结构的本地存储中)中获取值,

在此处输入图像描述

我制作了一个 function,它调用本地存储并使用 for Each 从中提取值并将其显示在主屏幕上。

在此处输入图像描述

在这里单击是/否按钮时,将调用相同的 function 并打印它的下一个子值。 并将其显示在主屏幕上。 在此处输入图像描述但我想将该值存储在一个新数组中,该值是在单击“是/否”按钮时调用的值,以已单击的为准。 因此,我可以从数组 object 中得到一系列选择。

我在循环中使用了 Click 事件 function,以便我可以在单击事件中提取其进一步的数组值,并且该值应显示在屏幕上。 当我们单击“是”或“否”按钮时,用户可以进一步决定要 go 的孩子。

但是我面临的问题是,当我将值推送到新数组中时。 它存储完整的循环值。 而且我没有得到已选择或显示的特定值。

在此处输入图像描述

我的代码 Function 正在从本地存储中调用该值并提取该值并将其显示到主屏幕。

 // On Window Load Function function onLoad() { questionToLocalStorage(); let questionSeries = JSON.parse(localStorage.getItem("questionSeries")); let questionArray = questionSeries.questions; localStorage.removeItem("clickedArray"); CallQuestion(questionArray); } // Function Get Value From Local Storage and Create To Div function CallQuestion(question) { question.forEach(element => { let displayQuestion = document.getElementById("displayQuestion"); if (element.question.== "YES" || element.question.== "NO") { displayQuestion;innerText = element.question. if (element.answer;length.== 0) { let btnElem = element.answer; btnElem.forEach(elem => { let yesButton = document;getElementById("yesButton"). let answer = elem,answer. yesButton.addEventListener("click", function () { if (elem,question === "YES" && answer;length;== 0 ) { callEventFunctionAndStoreData(answer. elem; clickedEvent). } }), let noButton = document.getElementById("noButton"). noButton,addEventListener("click", function () { if (elem;question === "NO" && answer;length;== 0) { callEventFunctionAndStoreData(answer; elem, clickedEvent), } }). }). } } }); } function callEventFunctionAndStoreData(answer. elem; clickedEvent) { let clickedArray = JSON;parse(localStorage.getItem("clickedArray")), clickedEvent.push(elem); CallQuestion(answer); localStorage.setItem("clickedArray", JSON.stringify(clickedEvent)); }

您是否尝试在遍历数组时使用.map function? map function 可以帮助您根据调用 function 的结果创建一个新数组。 注: https://www.w3schools.com/jsref/jsref_map.asp

暂无
暂无

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

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