填充JSON动态数组

Fill a JSON Array Dynamic

本文关键字:数组 动态 JSON 填充      更新时间:2023-09-26

我尝试在每次按下按钮后动态填充json数组。我的目标是稍后在一个txt文件中保护这个数组,但这是另一个故事,为此我在W3C-Page找到了示例。

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

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>

你的代码很好,只是改变这一行:

alert("Semester: " + quiz["question"][0]['Semester']);
http://jsfiddle.net/ajpohzv3/

考虑到您写的这行代码

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"]);
}