我正在尝试创建一个对象数组,其中包含页面中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"
}
答案 0 :(得分:0)
您只需要修改以下行:
questionsAnswers.push({问题:questions [i] .textContent, 答案:答案[i]});
到
questionsAnswers.push({问题:questions [i] .textContent, 答案:answers [i] .value});
我希望它能起作用