js与jQuery实现获取table中的数据并拼成json字符串操作示例 本文实例讲述了js与jQuery实现获取table中的数据并拼成json字符串操作。分享给大家供大家参考,具体如下: 核心代码如下: JavaScript代码: function tabToJSON(id) { var trs = document.getElementById(id).getElementsByTagName("tr");//获得tr数组 var titles = trs[0].getElementsByTagName("td"); //获得表头td数组 var json = ""; for(var i = 1; i < trs.length; i++) { var tds = trs[i].getElementsByTagName("td"); json += "{"; //拼装json for(var j = 0; j < tds.length; j++) json += titles[j].innerHTML + ":" + tds[j].innerHTML + ","; json = json.substring(0, json.length - 1) + "},"; } json = "[" + json.substring(0, json.length - 1) + "]"; document.getElementById("test").innerHTML = json; } jQuery代码: function tabToJSONForJquery(id) { var titles = $("#" + id).find("tr:first td"); //获得表头td数组 //遍历非表头的,tr、td...拼装json var json = "[" + $("#" + id).find("tr:not(:first)").map(function(i, e) { return "{" + $(e).children("td").map(function(j, el) { return $(titles[j]).html() + ":" + $(el).html(); }).get().join(",") + "}"; }).get().join(",") + "]"; $("#test").html(json); } 注:为便于测试,建议jQuery直接使用cdn如: 测试HTML部分(table表格与json数据显示部分):
编号年龄单元房间号
12511-2
22211-1
32133-3
42022-2
53544-2
使用在线HTML/CSS/JavaScript代码运行工具:http://tools.zwyuanma.com/code/HtmlJsRun测试得到json数据为: [{编号:1,年龄:25,单元:1,房间号:1-2},{编号:2,年龄:22,单元:1,房间号:1-1},{编号:3,年龄:21,单元:3,房间号:3-3},{编号:4,年龄:20,单元:2,房间号:2-2},{编号:5,年龄:35,单元:4,房间号:4-2}] 感兴趣的朋友亲自动手测试一下看看效果如何 PS:这里再为大家推荐几款相关的json在线工具供大家参考: 在线JSON代码检验、检验、美化、格式化工具: http://tools.zwyuanma.com/code/json JSON在线格式化工具: http://tools.zwyuanma.com/code/jsonformat 在线XML/JSON互相转换工具: http://tools.zwyuanma.com/code/xmljson json代码在线格式化/美化/压缩/编辑/转换工具: http://tools.zwyuanma.com/code/jsoncodeformat 在线json压缩/转义工具: http://tools.zwyuanma.com/code/json_yasuo_trans 更多关于JavaScript相关内容可查看本站专题:《JavaScript中json操作技巧总结》、《JavaScript表格(table)操作技巧大全》、《JavaScript操作DOM技巧总结》、《JavaScript查找算法技巧总结》、《JavaScript错误与调试技巧总结》、《JavaScript数据结构与算法技巧总结》、《JavaScript遍历算法与技巧总结》及《JavaScript数学运算用法总结》 希望本文所述对大家JavaScript程序设计有所帮助。