0

我有问题数组,当我点击提交按钮时,我想在其中添加 HTML 表单数据,格式如下所示:

var questions = [
    new Question("What language are we learning today?", ["Java", "C#","C++", "JavaScript"], "JavaScript"),
    new Question("Which language is used for styling web pages?", ["HTML", "JQuery", "CSS", "XML"], "CSS")

];


HTML form that I have created         
   <form action="" method="post" >
            <label>Enter question:</label>
            <input type="text" id="question" name="question" /><br/>
            <label>Option1:</label>
            <input type="text" id="option1" name ="option1"/><br/>
            <label>Option2:</label>
            <input type="text" id="option2" name ="option2"/><br/>
            <label>Option3:</label>
            <input type="text" id="option3" name ="option3"/><br/>
            <label>Option4:</label>
            <input type="text" id="option4" name ="option4"/><br/>
            <label>Enter answer</label>
            <input type="text" id="answer" name="answer" /><br/>
            <input type="submit" name="submit" value="Add quiz" />

            </form>

所以,我想像这样将数据添加到数组中: new question("question?",["option1","option2","option3","option4"],"answer")

4

1 回答 1

1

你可以这样做:

function Question (pquestion, poptions, panswer) {
   this.question = pquestion;
   this.options = poptions;
   this.answer = panswer;
}

var questions = [
    new Question("What language are we learning today?", ["Java", "C#","C++", "JavaScript"], "JavaScript"),
    new Question("Which language is used for styling web pages?", ["HTML", "JQuery", "CSS", "XML"], "CSS")

];

function addQuestion() {
 var question = document.getElementById("qs").value;
 var option1 = document.getElementById("option1").value;
 var option2 = document.getElementById("option2").value;
 var option3 = document.getElementById("option3").value;
 var option4 = document.getElementById("option4").value;
 var answer = document.getElementById("answer").value;
 var numberOfQuestions = questions.length;
 questions[numberOfQuestions] = new Question(question, [option1, option2, option3, option4], answer);
 alert("Thank you. We now have " + questions.length + " questions.");
}
  <head>
  <title>test</title>
  </head>
  <body>
  
      <form>
            <label>Enter question:</label>
            <input type="text" id="qs" name="qs" /><br/>
            <label>Option1:</label>
            <input type="text" id="option1" name ="option1"/><br/>
            <label>Option2:</label>
            <input type="text" id="option2" name ="option2"/><br/>
            <label>Option3:</label>
            <input type="text" id="option3" name ="option3"/><br/>
            <label>Option4:</label>
            <input type="text" id="option4" name ="option4"/><br/>
            <label>Enter answer</label>
            <input type="text" id="answer" name="answer" /><br/>
            <input type="button" name="submit" onclick="addQuestion();" value="Add quiz" />

     </form>
 </body>

于 2019-06-21T20:47:20.030 回答