2017-03-18 56 views
-2

我想創建產生下面的HTML形式的JSON:生成以下表單的對象/數組格式是什麼?

<div class="row"> 
     <div class="column row-inner"> 
     <label>First name</label> 
     <input type="text" value=""> 
     </div> 
     <div class="column row-inner"> 
     <label>Last name</label> 
     <input type="text" value=""> 
     </div> 
    </div> 
    <div class="row"> 
     <div class="column row-inner"> 
     <label >Message</label> 
     <input type="text" value=""> 
     </div> 
    </div> 
    <div class="row"> 
     <div class="column column-big row-inner"> 
     <label>Message</label> 
     <input type="text" value=""> 
     </div> 
     <div class="column row-inner"> 
     <label>Message</label> 
     <input type="text" value=""> 
     </div> 
     <div class="column row-inner"> 
     <label>Message</label> 
     <input type="text" value=""> 
     </div> 
    </div> 

我想創建一個數組,並且具有內多個陣列:

schema: [{ // row 
    [{ // row-inner 
     name: 'First name', // label 
     type: 'text', // input 
    }, { 
     name: 'Last name', 
     type: 'text' 
    }] 
    }] 

但是,我發現它過於複雜(I我已經困惑了自己)。

有沒有人有更好的建議?

+0

成全它的對象數組的數組! '[[{name:...,type:...},{name:...,type:...}],[...],[...],...]' –

+0

這是一個無效的結構'[{[{....}]}]'如果'schema'應該包含多個表單''''''''var schema = [[{name:...,type: ...},...],[{name:..,type:...},...],...]' – Titus

回答

1
// the form array 
[ 
    // the first row 
    [ 
     // the first column 
     { 
      // the label 
      name: "First name", 
      // the input 
      type: "text" 
     }, 
     // the second column 
     { 
      name: "Last name", 
      type: "text" 
     } 
    ], 
    // the second row 
    [ 
     { 
      name: "Message", 
      type: "text" 
     } 
    ], 
    // the third row 
    [ 
     { 
      name: "Message", 
      type: "text" 
     }, 
     { 
      name: "Message", 
      type: "text" 
     }, 
     { 
      name: "Message", 
      type: "text" 
     } 
    ] 
] 

形式將是一個這樣的數組:

form = [row, row, row, row, ...] 

其中是一個這樣的數組:

row = [column, column, column, ...] 

是一個對象在這種格式:

column = { 
    name: "label's text", 
    type: "input's type" 
} 

jQuery代碼變換上述結構成一種形式:

var form = ...; 

var $form = $("<form></form>"); 
form.forEach(function(row) { 
    var $row = $("<div></div>") 
     .addClass("row") 
     .appendTo($form); 

    row.forEach(function(column) { 
     var $column = $("<div></div>") 
      .addClass("column row-inner") 
      .appendTo($row); 

     $("<label></label>").text(column.name).appendTo($column); 
     $("<input/>").attr("type", column.type).appendTo($column); 
    }); 
}); 

// append $form to a container 
1

如何人對象數組?

var people = []; 

function Person(firstName, lastName) { 
    this.firstName = firstName; 
    this.lastName = lastName; 
} 

var person = new Person('Foo', 'Bar'); 
people.push(person); 

console.log(people[0]); 
Person {firstName: "Foo", lastName: "Bar"} 

小提琴:https://jsfiddle.net/q1a7k30L/

相關問題