2015-06-01 154 views
1

我尝试每次按下按钮后动态填充json数组。我的目标是后来在txt文件中保证这个数组安全,但这是另外一个故事,因此我在W3C-Page上找到了一些例子。填充JSON数组动态

这是到目前为止我的代码:

enter 
<html> 
<body> 

<table> 
    <tr> 
     <td><label>Subject: <input id="subject" type="text" /></label></td> 
     <td><label>Semester: <input id="semester" type="text" /></label></td> 
     <td><label>Name: <input id="name" type="text" /></label></td> 
    </tr> 
    <tr> 
     <td> 
      <label>Question: <label> 
     </td> 
     <td colspan="2"> 
      <textarea id="question" style="width:512px;height:100px"></textarea> 
     </td> 
    </tr> 
    <tr> 
     <td> 
      <label>Answer 1: <label> 
     </td> 
     <td colspan="2"> 
      <textarea id="Answer1" style="width:512px;height:100px"></textarea> 
     </td> 
    </tr> 
    <tr> 
     <td> 
      <label>Answer 2: <label> 
     </td> 
     <td colspan="2"> 
      <textarea id="Answer2" style="width:512px;height:100px"></textarea> 
     </td> 
    </tr> 
    <tr> 
     <td> 
      <label>Answer 3: <label> 
     </td> 
     <td colspan="2"> 
      <textarea id="Answer3" style="width:512px;height:100px"> </textarea> 
     </td> 
    </tr> 
    <tr> 
     <td> 
      <label>Answer 4: <label> 
     </td> 
     <td colspan="2"> 
      <textarea id="Answer4" style="width:512px;height:100px"> </textarea> 
     </td> 
    </tr> 
    <tr> 
     <td></td> 
     <td><button onclick="saveInputInArray()">Save in Array</button></td> 
     <td></td> 
    </tr> 
</table> 

<script type='text/javascript'> 

var quiz = { 
    question:[] 
}; 

function saveInputInArray() 
{ 
    quiz.question.push({ 
     "Subject" : document.getElementById("subject").value, 
     "Semester" : document.getElementById("semester").value, 
     "Name" : document.getElementById("name").value, 
     "Question" : document.getElementById("question").value, 
     "Answer1" : document.getElementById("Answer1").value, 
     "Answer2" : document.getElementById("Answer2").value, 
     "Answer3" : document.getElementById("Answer3").value, 
     "Answer4" : document.getElementById("Answer4").value 
    }); 

    alert("Semester: " + quiz["question"]["semester"]); 
} 

</script> 

</body> 
</html> 
+2

你不“填充json数组”。 json是一种传输编码格式。你填充一个javascsript数组,然后在完成填充时将其编码为json。 –

回答

1

考虑到这行代码是你写

alert("Semester: " + quiz["question"]["semester"]); 

我会这样做:

var quiz = { 
    question:[] 
}; 

function saveInputInArray() 
{ 

    "subject semester name question Answer1 Answer2 Answer3 Answer4".split(" ").forEach(function(id){ 
     quiz.question[id] = document.getElementById(id).value; 
    }); 

    alert("Semester: " + quiz["question"]["semester"]); 
} 
+0

我也感谢你的帮助 – Mangooxx

+0

谢谢你的谢意;) – Abrab