如何使用jquery每个HTML dom和get属性转成JSON [英] How to use jquery each the HTML dom and get attribute turn into JSON
本文介绍了如何使用jquery每个HTML dom和get属性转成JSON的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想获取html dom属性,并在提交表单时变为JSON。
I want to get html dom attribute and turn into JSON when submit the form.
这是html表单元素:
Here is the html form element:
<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]
}
}
}]
推荐答案
p>尝试这样:
$(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/
这篇关于如何使用jquery每个HTML dom和get属性转成JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文