var _jq, _hc; var jqsrc = "http://code.jquery.com/jquery-1.7.min.js"; var hcsrc = "http://code.highcharts.com/highcharts.js"; function checkJquery() { if(typeof(jQuery) == "function") { window.clearInterval(_jq); initHighcharts(); } } function checkHighcharts() { if(typeof(jQuery("body").highcharts) == "function") { window.clearInterval(_hc); initTochart(); } } function initJquery() { if(typeof(jQuery) != "function") { var jq = document.createElement("script"); jq.type = "text/javascript"; jq.src = jqsrc; document.body.appendChild(jq); _jq = window.setInterval(checkJquery, 500); } else { initHighcharts(); } } function initHighcharts() { if(typeof(jQuery("body").highcharts) != "function") { var hc = document.createElement("script"); hc.type = "text/javascript"; hc.src = hcsrc; document.body.appendChild(hc); _hc = window.setInterval(checkHighcharts, 500); } else { initTochart(); } } function initTochart() { jQuery.fn.tochart = function(x, s) { var title = {}, data = {}; jQuery.each(jQuery(this).find("tr:first").find("th"), function(i, o) { title[i] = jQuery(o).text(); }); if(x == undefined) x = 0; else if(typeof(x) == "string") { for(var i in title) { if(title[i] == x) x = i; } } var rows = jQuery(this).find("tr"); if(typeof(s) == "boolean") { rows.sort(function(a, b) { return jQuery(a).find("td:eq(" + x + ")").text().localeCompare(jQuery(b).find("td:eq(" + x + ")").text()) * (s ? 1 : -1); }); } jQuery.each(rows, function(i, o) { jQuery.each(jQuery(o).find("td"), function(j, p) { if(data[j] == undefined) { data[j] = []; } if(j == x) { data[j].push(jQuery(p).text()); } else if(!isNaN(jQuery(p).text())) { data[j].push(parseFloat(jQuery(p).text())); } else { data[j].push(0); } }); }); var ys = []; for(var i in title) { if(x != i) { ys.push({name: title[i], data: data[i]}); } } jQuery("body").append("<div id=\"__chart\" style=\"display: block;\"></div>"); jQuery("#__chart").highcharts({ title: { text: "" }, credits: { enabled: false }, xAxis: { categories: data[x] }, series: ys, tooltip: { formatter: function() { return this.x + "<br />" + this.series.name + ": " + this.y; } } }); } } initJquery();
用法: $("table").tochart("日期", true); //以日期为x轴并按升序排序