Js table generator with buttons

我与影子孤独终老i 提交于 2020-05-14 02:25:33

问题


I found this answer on the website.

I was trying to get the buttons to render within the table but it just came up as text.

Here's the code:

function tableCreate() {
  var body = document.getElementsByTagName("body")[0];

  var tbl = document.createElement("table");
  var tblBody = document.createElement("tbody");

  for (var j = 0; j <= 10; j++) {
    var row = document.createElement("tr");

    for (var i = 0; i <10; i++) {
      var cell = document.createElement("td");
      var btn = "<button>" + j +"-"+i+"</button>"
      var cellText = document.createTextNode(btn);

      cell.appendChild(cellText);
      row.appendChild(cell);
    }
    tblBody.appendChild(row);
  }
  tbl.appendChild(tblBody);
  body.appendChild(tbl);
  tbl.setAttribute("border", "2");
}

function cell_id(x,y){
  msg('x:'+x+ ' y:'+y)
}

回答1:


createTextNode() creates a text node, as the name says. If you have markup in it, it will be shown literally.

You should create a button node, and set its text to the variables.

    for (var i = 0; i <10; i++) {
      var cell = document.createElement("td");
      var btn = document.createElement("button");
      btn.innerText = j + "-" + i;
      cell.appendChild(btn);
      row.appendChild(cell);
    }



回答2:


Use document.createElement('button') for creating buttons. You are just creating textNodes using createTextNode().




回答3:


You need to create a button node and then append it.

function tableCreate() {
  var body = document.getElementsByTagName("body")[0];

  var tbl = document.createElement("table");
  var tblBody = document.createElement("tbody");

  for (var j = 0; j <= 10; j++) {
    var row = document.createElement("tr");

    for (var i = 0; i <10; i++) {
      var cell = document.createElement("td");
      var button document.createElement("button");
      button.innerHTML = j +"-"+i;
      cell.appendChild(button);
      row.appendChild(cell);
    }
    tblBody.appendChild(row);
  }
  tbl.appendChild(tblBody);
  body.appendChild(tbl);
  tbl.setAttribute("border", "2");
}

function cell_id(x,y){
  msg('x:'+x+ ' y:'+y)
}


来源:https://stackoverflow.com/questions/61549116/js-table-generator-with-buttons

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!