javascript - 从 DOM 元素和输入元素的值创建一个带有文本内容的对象?
问题描述
我正在尝试使用来自我的页面的 HTML 元素(标签)的文本内容的值和来自表单输入的值创建一个对象数组。
该对象显示在 console.log 上,但值中没有任何内容,它显示为“0”。
//JavaScript
//answers value for the object
const answers = document.querySelectorAll("#questions input");
//questions value for the object
const questions = document.querySelectorAll("#questions label");
const questionsAnswers = [];
const wrongQuestions = [];
const displayDiv = document.getElementById("display");
theQuestions.addEventListener("submit", (e)=>{
for(let i = 0; i<questions.length; i++){
//this is where the object gets created, where the problem occurs
questionsAnswers.push({ question: questions[i].textContent,
answer: answers[i]});
console.log(questionsAnswers[i]);
}//end of for loop
e.preventDefault();
});// end of event listener
//HTML
<form id="theQuestions" style="height:500px">
<div class="form-group">
<label for="question1">What is the NBA team in Georgia?</label>
<input type="text" class="form-control" id="question1">
</div>
<div class="form-group">
<label for="question2">What is the name of the NFL team in
North Carolina?</label>
<input type="text" class="form-control" id="question2">
</div>
<div class="form-group">
<label for="question3">What team did Micheal Jordan play for?
</label>
<input type="text" class="form-control" id="question3">
</div>
<button type="submit" class="btn btn-outline
primary">Submit</button>
</form>
//I want the object to look like this
{
answer: "text content of the first <label> element",
question: "form input value from the first input element"
},
{
answer: "text content of the 2nd <label> element",
question: "form input value from the 2nd input element"
},
{
answer: "text content of the 3rd <label> element",
question: "form input value from the 3rd input element"
}
解决方案
你只需要修改这一行:
questionsAnswers.push({ 问题:问题[i].textContent,答案:答案[i]});
至
questionsAnswers.push({ 问题:问题[i].textContent,答案:答案[i].value});
我希望它会工作
推荐阅读
- powershell - 如何使用 PowerShell 工作流和检查点来实现可恢复性
- python - 迭代 Pandas 数据框中的行,保持前 2 行固定
- node.js - GCloud 中的 NodeJS 错误:找不到 openssl 路径
- c# - 具有多个 ReferencePaths 的 Resharper InspectCode
- entity-framework - 将返回 Func 的方法添加到实体框架模型会导致 InvalidOperationException 异常
- javascript - 角度 8 拖放 CDK 中的 DOM 异常
- php - 如何使用 PHP 从我的网站从 Windows 机器访问 Windows 服务或数据?
- java - 通过给定的正则表达式生成一个新字符串
- google-play - 我可以跟踪 Playstore 中应用程序的下载次数吗?
- microsoft-cognitive - Azure 认知服务 - 无法在表单识别器中选择位置或定价层