什么是一个好的对象/数组格式来生成以下形式?

时间:2017-03-18 12:13:52

标签: javascript html

我想创建一个生成以下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'
    }]
  }]

然而,我发现它过于复杂(我已经把自己搞糊涂了)。

有没有人有更好的建议?

2 个答案:

答案 0 :(得分: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 :(得分: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/