填充JSON数组动态

时间:2015-06-01 21:31:23

标签: javascript arrays json dynamic

每次按下按钮后,我都会尝试动态填充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>

2 个答案:

答案 0 :(得分:1)

您的代码很好,只需更改此行:

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

http://jsfiddle.net/ajpohzv3/

答案 1 :(得分: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"]);
}