如何“tblGene()”调用JavaScript页面。我想使用onclick在HTML页面上调用..没有在我的网页上单击此Json表格显示

时间:2017-01-24 08:17:42

标签: javascript html

tblGene()如何调用JavaScript页面。我不想使用onclick来调用HTML页面。没有点击,这个JSON表格会显示在我的网页上。请帮我。页面在我的网页上加载了这个JSON表。我不想使用输入框进行点击。

<input type="button" onclick="tblGene()" value="Click Here to Generate Table" style="width:100% height:100%" />
    <div id="showData"></div>

    var people, asc1 = 1; 
function tblGene() {
  var data = [{"rollno":1234,'name': "jetta",'marks': 600,'percentage': 1222,'bestscore': 99},{"rollno":2341,'name': "jetta",'marks': 700,'percentage': 1222,'bestscore': 100},{"rollno":3421,'name': "jetta",'marks': 500,'percentage': 1222,'bestscore': 90},{"rollno":4321,'name': "jetta",'marks': 400,'percentage': 1222,'bestscore': 95},{"rollno":2043,'name': "jetta",'marks': 550,'percentage': 1222,'bestscore': 80},];
  var thead = document.createElement('thead');
  var tbody = document.createElement('tbody');
  tbody.id = "people";
  var tbl = document.createElement("table");
  tbl.id = "tblSample";
  var col = [];
  for (var i = 0; i < data.length; i++) {
    for (var colHdr in data[i]) {
      if (col.indexOf(colHdr) === -1) {
        col.push(colHdr);
      }
    }
  }          
  var tr = tbl.insertRow(-1);
  for (var i = 0; i < col.length; i++) {
    var th = document.createElement("th");
    th.innerHTML = col[i];
    th.dataset.key = i;
    tr.appendChild(th);
  }
  thead.appendChild(tr);
  for (var i = 0; i < data.length; i++) {
    tr = tbl.insertRow(-1);
    for (var j = 0; j < col.length; j++) {
      var td = document.createElement("td");
      var tabCell = tr.insertCell(-1);
      tabCell.innerHTML = data[i][col[j]];
    }
    tbody.appendChild(tr);
  }
  tbl.appendChild(thead);
  tbl.appendChild(tbody);
  var divCntr = document.getElementById("showData");
  divCntr.innerHTML = "";
  divCntr.appendChild(tbl);
  thead.addEventListener("click", function(event) {
    var key = event.target.dataset.key;
    people = document.getElementById("people");
    sort_tbl(people, key, asc1);
  });
  function sort_tbl(tblSample, key, asc) {
    var rows = tblSample.rows,
      rlen = rows.length,
      arr = new Array();
    for (var i = 0; i < rlen; i++) {
      var cells = rows[i].cells;
      var clen = cells.length;
      arr[i] = new Array();
      for (var j = 0; j < clen; j++) {
        arr[i][j] = cells[j].innerHTML;
      }
    }
    arr.sort(function(x, y) {
      if (isNaN(x[key]) && isNaN(y[key])) {
        var a = String(x[key]).toUpperCase();
        var b = String(y[key]).toUpperCase();
        if (a > b)
          return 1
        if (a < b)
          return -1
        return 0;
      } else {
        return x[key] - y[key];
      }
    });
    for (i = 0; i < rlen; i++) {
      rows[i].innerHTML = "<td>" + arr[i].join("</td><td>") + "</td>";
    }
  }
}

1 个答案:

答案 0 :(得分:0)

只需从您的onclick处理程序中删除(),例如onclick="tblGene"

如果您离开(),则在加载<input>元素后立即执行该功能 - 在您加载页面的情况下。