js获取table中的数据并拼成json字符串

 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;
    }


    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);
    }

你可能感兴趣的:(获取table数据)