簡體   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