js与jQuery实现获取table中的数据并拼成json字符串操作示例

本文实例讲述了js与jQuery实现获取table中的数据并拼成json字符串操作。分享给大家供大家参考,具体如下:

核心代码如下:

JavaScript代码

rush:js;"> 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代码

rush:js;"> 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如:

rush:js;">

相关文章

页面搜索关键词突出 // 页面搜索关键词突出 $(function () {...
jQuery实时显示日期、时间 html: &lt;span id=&quot...
jQuery 添加水印 &lt;script src=&quot;../../../.....
中文:Sys.WebForms.PageRequestManagerParserErrorExceptio...
1. 用Response.Write方法 代码如下: Response.Write(&q...
Jquery实现按钮点击遮罩加载,处理完后恢复 思路: 1.点击按...