我是 JavaScript 初学者,在这项任务中我必须执行以下操作;
- 允许用户在 html 页面中输入问题和答案对,该页面将存储在数组中。
- 当询问数组中的一个问题时检索答案(不同的框、标签)
- 按下按钮时重置框
到目前为止,我只知道如何将用户输入存储在一个数组中,在按下按钮时追加它并显示它。
如何在同一个数组中拥有两个不同的对象(问题和答案),这两个对象将由用户成对输入,并在再次输入问题时仅检索答案? 它的工作原理类似于手动机器人。
var myArr = [];
function pushData() {
// get value from the input text
var inputText = document.getElementById('inputText').value;
// append data to the array
myArr.push(inputText);
var pval = "";
for (i = 0; i < myArr.length; i++) {
pval = pval + myArr[i] + "<br/>";
}
// display array data
document.getElementById('pText').innerHTML = pval;
}
<!DOCTYPE html>
<html>
<head>
<title</title>
<meta charset="windows-1252">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<input type="text" name="text" id="inputText" />
<button onclick="pushData();">Show</button>
<p id="pText"></p>
</body>
</html>
最佳答案
为什么不使用对象呢?这样,您就可以存储问题/答案对,其中问题作为键,答案作为其值。试试这个:
var myObj = {};
function pushData() {
// get value from the input text
var question = document.getElementById('inputQuestion').value;
var answer = document.getElementById('inputAnswer').value;
// add data to the object
myObj[question] = answer;
}
function getAnswer() {
var question = document.getElementById('inputRetrieveQuestion').value;
if (myObj[question]) {
document.getElementById('pText').innerHTML = myObj[question];
}
}
<html>
<body>
<h3> Enter a Question/Answer </h3>
Question <input type="text" name="question" id="inputQuestion" /> Answer <input type="text" name="answer" id="inputAnswer" />
<button onclick="pushData()">Submit</button>
</br>
<h3> Retrieve an Answer </h3>
Question <input type="text" name="question" id="inputRetrieveQuestion" />
<button onclick="getAnswer()">Submit</button>
</br>
Answer:
<div id="pText"></div>
</body>
</html>
关于javascript - 将用户输入(问答)存储在数组中并检索答案,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46658258/