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数据显示部分):
编号 | 年龄 | 单元 | 房间号 |
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 |