首页 > 解决方案 > 从 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"
 }

标签: javascriptarraysobject

解决方案


你只需要修改这一行:

questionsAnswers.push({ 问题:问题[i].textContent,答案:答案[i]});

questionsAnswers.push({ 问题:问题[i].textContent,答案:答案[i].value});

我希望它会工作


推荐阅读