是否可以将JavaScript数组元素超链接到HTML表中?

时间:2017-08-17 23:13:32

标签: javascript html arrays html-table

这是我到目前为止所做的代码。我想超链接网站,以便当数组作为HTML表格输出时,网站将是可点击的并链接到他们各自的网页。出于某种原因,type =“text / javascript”中的代码与language =“JavaScript”中的代码不同,我不知道为什么。如果有人可以提供language =“JavaScript”的代码,那将非常感激!

HTML:

<table id="table">
  <tr id="tbody">
    <th>Mattress Type</th>
    <th>Link</th>
  </tr>
</table>

JAVASCRIPT:

<script language="JavaScript">

var table = document.getElementById("table");
var body = document.createElement("tbody");

var beds = new Array(3);
beds[0] = ["Spring Mattress", "King Size", "http://factorymattresstexas.com/specials/spring-air/"];
beds[1] = ["Rest Lumbar Support", "Queen Size", "http://factorymattresstexas.com/specials/beautyrest-lumbar-support"];
beds[2] = ["Beauty Rest", "Twin Size", "http://factorymattresstexas.com/specials/simmons-beautyrest/"];

table.appendChild(tbody);
beds.forEach(function(items) {
  var row = document.createElement("tr");
  items.forEach(function(item) {
    var cell = document.createElement("td");
    cell.textContent = item;
    row.appendChild(cell);
  });
  table.appendChild(row);
});
</script>

1 个答案:

答案 0 :(得分:2)

你几乎就在那里。您只需要继续添加子元素:

&#13;
&#13;
var table = document.getElementById("table");
var body = document.createElement("tbody");

// initialize an empty array
var beds = [];

// add bed objects to the array
beds.push({
  type: "Spring Mattress",
  size: "King Size",
  link: "http://factorymattresstexas.com/specials/spring-air/"
});
beds.push({
  type: "Rest Lumbar Support",
  size: "Queen Size",
  link: "http://factorymattresstexas.com/specials/beautyrest-lumbar-support"
});
beds.push({
  type: "Beauty Rest",
  size: "Twin Size",
  link: "http://factorymattresstexas.com/specials/simmons-beautyrest/"
});

table.appendChild(tbody);
beds.forEach(function(item) {
  var row = document.createElement("tr");

  // You were previously just dumping the whole array contents in a cell.  Most likely you want to have separate cells for each type of information.
  var type = document.createElement("td");
  type.textContent = item.type;

  var size = document.createElement("td");
  size.textContent = item.size;

  // Create the containing cell to hold the link
  var link_td = document.createElement("td");

  // Create the <a href="...">...</a> element
  var link = document.createElement("a");
  link.textContent = item.link;
  link.href = item.link

  // Add the link to the cell
  link_td.appendChild(link);

  // Add the cells to the row in the order you'd like to see them in
  row.appendChild(type);
  row.appendChild(size);
  row.appendChild(link);

  table.appendChild(row);
});
&#13;
<table id="table">
  <tr id="tbody">
    <th>Mattress Type</th>
    <th>Size</th>
    <th>Link</th>
  </tr>
</table>
&#13;
&#13;
&#13;

<强>更新: 你的床阵是一系列字符串。我把它切换成使用一系列床对象。这允许您定义属性并按名称而不是索引引用这些属性(即item.size vs item[1])。这更干净,随着代码库的增长,它会更好地扩展。您可以使用要显示的其他属性扩展床对象。