【问题标题】:How to use jquery each the HTML dom and get attribute turn into JSON如何使用 jquery 每个 HTML dom 并获取属性转换为 JSON
【发布时间】:2012-10-10 17:18:09
【问题描述】:

我想在提交表单时获取 html dom 属性并转换为 JSON。

这里是html表单元素:

<div data-role="fieldcontain">
    <fieldset data-role="controlgroup" data-type="vertical" data-mini="true">
        <legend>1、question1?</legend>
        <input name="yes" id="checkbox5"
        type="checkbox">
        <label for="checkbox5">yes</label>
        <input name="no" id="checkbox16" type="checkbox">
        <label for="checkbox16">no</label>
    </fieldset>
</div>
<div data-role="fieldcontain">
    <fieldset data-role="controlgroup" data-type="vertical" data-mini="true">
        <legend>2、question2?</legend>
        <input name="below_60" id="checkbox9"
        type="checkbox">
        <label for="checkbox9">60</label>
        <input name="btw_60_80" id="checkbox13" type="checkbox">
        <label for="checkbox13">60-80</label>
        <input name="btw_80_100" id="checkbox14" type="checkbox">
        <label for="checkbox14">80-100</label>
    </fieldset>
</div>

而 JSON 是这样的:

[{
    {
        "question": "1、question1?",
        "ask": {
            ["type": "checkbox", "name": "yes", "value": "yes", "isChecked": 0], ["type": "checkbox", "name": "no", "value": "no", "isChecked": 1]
        }
    },{
        "question": "2、question2?",
        "ask": {
            ["type": "checkbox", "name": "below_60", "value": "60", "isChecked": 1], ["type": "checkbox", "name": "btw_60_80", "value": "60-80", "isChecked": 1], ["type": "checkbox", "name": "btw_80_100", "value": "80-100", "isChecked": 1]
        }
    }
 }]

【问题讨论】:

  • 看起来您正在混淆 [] 的(数组)和 {} 的(对象)

标签: javascript jquery json dom


【解决方案1】:

看来http://api.jquery.com/serialize/ 或许能帮到你。

【讨论】:

    【解决方案2】:

    试试这个:

    $(function(){
        var data = [];
        $('fieldset').each(function(){
            var fieldset = $(this);
            var item = { question: fieldset.find('legend').text(), ask: [] };
            fieldset.find('input').each(function(){
                var input = $(this);
                item.ask.push({ type: input.attr('type'), name: input.attr('name'),
                            isChecked: input.is(':checked') ? '1' : '0',
                            value: fieldset.find('[for="' + input.attr('id') + '"]').text() });
            });
            data.push(item);
        });
        console.log(data);
    });
    

    演示:http://jsfiddle.net/Qf3pX/

    【讨论】:

      猜你喜欢
      • 2013-06-19
      • 1970-01-01
      • 2014-03-26
      • 1970-01-01
      • 2017-12-01
      • 1970-01-01
      • 1970-01-01
      • 2016-07-31
      • 1970-01-01
      相关资源
      最近更新 更多