【问题标题】:How do I display a dynamically created html table only once?如何只显示一次动态创建的 html 表?
【发布时间】:2019-12-11 19:53:21
【问题描述】:

每次我输入另一个足球比分时,联赛表都会更新并显示,但它会附加到表格列表中。如何只显示最新的表格?

这里是 html 的摘录:

<div>
<table id="matches" border="1"> </table>
</div>
<div>
<table id="standings" border="1"> </table>
</div>
<input type="button" value="Update" onclick="update()" />

这是显示用于输入分数的装置的 javascript:

// Display fixtures to input the scores

window.onload = function()
{
table = document.getElementById("matches");

var row;
var cell1;
var cell2;
var cell3;

  for (i = 1; i < Results.length; i++)
  {

    row = table.insertRow(i-1); //table starts row 0 but Results row 1 so i-1 used
    cell1 = row.insertCell(0);
    cell2 = row.insertCell(1);
    cell3 = row.insertCell(2);
    cell4 = row.insertCell(3);
    cell1.innerHTML = Results[i][0];
    cell2.innerHTML = '<input type="number" min="0" max="99"/>'
    cell3.innerHTML = '<input type="number" min="0" max="99"/>'
    cell4.innerHTML = Results[i][3];
  }
}

这是在输入最新分数后显示表格的代码:

// Display League Table

standings = document.getElementById("standings");


for (i = 0; i < League.length; i++)
{

    row = standings.insertRow(i);
    cell1 = row.insertCell(0);
    cell2 = row.insertCell(1);
    cell3 = row.insertCell(2);
    cell4 = row.insertCell(3);
    cell5 = row.insertCell(4);
    cell6 = row.insertCell(5);
    cell7 = row.insertCell(6);
    cell8 = row.insertCell(7);
    cell1.innerHTML = League[i][0];
    cell2.innerHTML = League[i][1];
    cell3.innerHTML = League[i][2];
    cell4.innerHTML = League[i][3];
    cell5.innerHTML = League[i][4];
    cell6.innerHTML = League[i][5];
    cell7.innerHTML = League[i][6];
    cell8.innerHTML = League[i][7];
}

输入三个分数后显示如下:

我尝试在 javascript 中清除联赛数组,但结果仍然相同。我如何只显示表格的顶级版本?谢谢

【问题讨论】:

  • row 是在哪里创建的,i 是在哪里声明的?请在此处添加更多代码,因为这个 sn-p 并不足以很好地帮助您。
  • 开始前为什么不清表呢?
  • 感谢@MarkSchultheiss Row 是在显示灯具时创建的。我已将该代码添加到问题中。
  • 干杯@jhpratt 这很有意义,但我不确定如何做到这一点,确切地说。我会使用另一个将“”分配给每个单元格的循环吗?
  • 似乎您应该简单地创建表格并更新单元格 - 除非您需要所有这些,听起来您不需要。

标签: javascript html-table duplicates display


【解决方案1】:

对于您的表格更新/问题,请关注updateRow 函数。此行实际更新行 rownum column(&lt;td&gt;) i

的内容

rows[rownum].getElementsByTagName('td')[i].innerHTML = coldata[i];

这里不仅仅是更新表格行,您可以查看我的名称空间对象中的函数updateRowupdateRow 调用 createRow 如果需要(该索引处的行不存在),这里没什么特别的,然后更新新行。

我在命名空间中使用matches 中创建的匹配对象数组(不是问题中的对象,所以我做了假设):

matches: [{
  match: 1,
  score: [{
    team: "Ap",
    score: 3
  }, {
    team: "Or",
    score: 2
  }]
}],

请注意,我在哪里调用此代码来更新表中 standings 的表,并带有 standings-table id。我不知道这些是什么,所以我只是在数组中插入了一些东西,然后使用

更新表
for (let i = 0; i < myLeague.standings.length; i++) {
    myLeague.updateRow('standings-table', myLeague.standings[i], i);
}

其他事情:我创建表单只是为了展示如何在插入新匹配时更新表格,我触发了一个事件,它会执行更新或插入行所需的操作 - 但实际上这只是为了测试在创建新匹配时更新。

  • 表中的行是否更新或插入完全取决于matches 内容的数组
  • 没有处理表或数组中的删除,因为这只是插入和更新
  • 如果匹配索引的行索引不存在,它会创建一个新行并更新它

var myLeague = myLeague || {
  teamSelect1: "team1",
  teamSelect2: "team2",
  matchesPlayed: 1,
  teams: [{
      name: "Apples",
      abbreviation: "Ap"
    },
    {
      name: "Oranges",
      abbreviation: "Or"
    },
    {
      name: "Pears",
      abbreviation: "Pe"
    }
  ],
  matches: [{
    match: 1,
    score: [{
      team: "Ap",
      score: 3
    }, {
      team: "Or",
      score: 2
    }]
  }],
  standings: [
    ["A", 2, 1, 1, 3, 2, 3, 0],
    ["B", 3, 1, 1, 3, 2, 3, 6]
  ],
  cloneRow: function(tableid, objectRef) {
    // find table to clone/append to
    let table = document.getElementById(tableid);
    // find row to clone, I use first one
    let firstRow = mytable.rows[0];
    // let row = document.getElementById("rowToClone");
    let clone = firstRow.cloneNode(true); // copy children too
    clone.id = ""; // change id or other attributes/contents
    table.appendChild(clone); // add new row to end of table
  },
  createRow: function(tableid, colCount, rowCount = 1, defaultContent = "") {
    let row = document.createElement('tr'); // create row node
    for (let i = 0; i < colCount; i++) {
      let newText = document.createTextNode(defaultContent);
      let col = row.insertCell(i);
      col.appendChild(newText);
    }
    let table = document.getElementById(tableid); // find table to append to
    let tbody = table.getElementsByTagName('tbody')[0];
    for (let r = 1; r <= rowCount; r++) {
      tbody.appendChild(row); // append row to table
    }
  },

  updateRow: function(tableid, coldata = ['$nbsp;'], rownum = 0) {
    let table = document.getElementById(tableid); // find table to update to
    let tbody = table.getElementsByTagName('tbody')[0];
    let rows = tbody.rows; // get rows node
    let maxRows = 20; //keep it from going crazy adding rows
    while (rows.length < maxRows && !rows[rownum]) {
      this.createRow(tableid, coldata.length, 1, "x");
    }
    //myLeague.updateRow(tableid,coldata, rownum);
    for (let i = 0; i < coldata.length; i++) {
      rows[rownum].getElementsByTagName('td')[i].innerHTML = coldata[i];
    }
  },
  addTeam: function(team, teamid) {
    var sel = document.getElementById(teamid);
    var optNew = document.createElement("option");
    optNew.value = team.abbreviation;
    optNew.text = team.name;
    sel.add(optNew, null);
  },
  addTeamsToSelect: function() {
    myLeague.teams.forEach(function(team) {
      myLeague.addTeam(team, this.teamSelect1);
      myLeague.addTeam(team, this.teamSelect2);
    }, this);
  },
  listMatches: function(event) {
    // event.target is the div
    let src = event.target.dataset.source;
    console.log("src:", src);
    document.getElementById("matchplayed").textContent = event.matches;
    this[src].forEach(function(item, index, array) {
      document.getElementById('matchplayed').textContent = array.length;
      let rowdata = [item.score[0].team, item.score[0].score, item.score[1].team, item.score[1].score];
      this.updateRow(src, rowdata, index);
    }, this);
  },

  clickAddListener: function(event) {
    // 'this' is bound to the namespace object
    // console.log(event.target); // the button
    // console.log(this.matchesPlayed);//namespace
    if (!document.getElementById(this.teamSelect1).value || !document.getElementById(this.teamSelect2).value) {
      let errorEl = document.getElementById("form1")
        .getElementsByClassName("error-text")[0];
      errorEl.textContent = "Both teams need to be selected.";
      errorEl.style.visibility = 'visible';
      errorEl.style.opacity = '1';
      setTimeout(function() {
        errorEl.style.WebkitTransition = 'visibility .5s, opacity .5s';
        errorEl.style.opacity = '0';
        errorEl.style.visibility = 'hidden';
        errorEl.textContent = "";
      }, 5000);
    } else {
      this.matchesPlayed++;
      let r = {
        match: this.matchesPlayed,
        score: [{
          team: document.getElementById(this.teamSelect1).value,
          score: document.getElementById("score1").value
        }, {
          team: document.getElementById(this.teamSelect2).value,
          score: document.getElementById("score2").value
        }]
      };
      this.matches.push(r);
    }
    document.getElementById('matches').dispatchEvent(this.showmatchesevent);
  },
  addListeners: function() {
    let scope = this;

    document.getElementById(this.teamSelect1)
      .addEventListener('change', function() {
        let s = document.getElementById(scope.teamSelect2);
        let oval = s.value;
        if (this.value == oval) {
          s.value = '';
        }
      }, this);

    document.getElementById(this.teamSelect2)
      .addEventListener('change', function() {
        let s = document.getElementById(scope.teamSelect1);
        let oval = s.value;
        if (this.value == oval) {
          s.value = '';
        }
      }, this);

    document.getElementById('add-match')
      // bind this namespace to the event listener function
      .addEventListener('click', (this.clickAddListener).bind(this), false);

    this.showmatchesevent = new CustomEvent('showmatches');
    document.getElementById('matches')
      .addEventListener('showmatches', this.listMatches.bind(this), false);
  }
};
window.onload = function() {
  myLeague.addTeamsToSelect();
  myLeague.addListeners();
  for (let i = 0; i < myLeague.standings.length; i++) {
    myLeague.updateRow('standings-table', myLeague.standings[i], i);
  }
  // set table from defaults/imported list
  document.getElementById('matches').dispatchEvent(myLeague.showmatchesevent);
};
/* typography */

html {
  font-family: 'helvetica neue', helvetica, arial, sans-serif;
}

th {
  letter-spacing: 2px;
}

td {
  letter-spacing: 1px;
}

tbody td {
  text-align: center;
}

.match-inputs {
  border: solid 2px #DDDDDD;
  padding;
  1em;
  margin: 1em;
}

.error-text {
  height: 1em;
  color: red;
}

.matches-played {
  padding: 13m;
}


/* table layout */

table {
  border-collapse: collapse;
  border: 1px solid black;
}

.score th,
td {
  padding: 0.2em;
  border: solid #DDDDDD 1px;
}

.container {
  padding: 1em;
}
<div class="container match-inputs">
  <form id="form1">
    <div>Add Matches</div>
    <div class="input-group"><label>Choose L Team:</label>
      <select id="team1">
        <option value="">Choose</option>
      </select>
    </div>
    <div class="input-group"><label>Choose L2 Team:</label>
      <select id="team2">
        <option value="">Choose</option>
      </select>
    </div>
    <div class="input-group score-group"><label>Team1 score:</label>
      <input id="score1" type="number" class="score-input" value="0" min="0" max="99" value="0" />
    </div>
    <div class="input-group score-group"><label>Team2 score:</label>
      <input id="score2" type="number" class="score-input" value="0" min="0" max="99" value="0" />
    </div>
    <div class="input-group"><label>Add this match to the list.</label>
      <button type="button" id="add-match">Add Match</button>
    </div>
    <div class="error-text">&nbsp;</div>
  </form>
</div>
<div class="container">
  <div class="matches-played">Matches Played:<span id="matchplayed"></span></div>
  <table id="matches" data-source="matches">
    <thead>
      <tr>
        <th colspan="4">Matches</th>
      </tr>
      <tr>
        <th>L</th>
        <th>S</th>
        <th>S2</th>
        <th>L1</th>
      </tr>
    </thead>
    <tbody>
      <tr>
        <td></td>
        <td></td>
        <td></td>
        <td></td>
      </tr>
    </tbody>
  </table>
</div>
<div class="container">
  <table id="standings-table">
    <thead>
      <tr>
        <th colspan="8">Standings</th>
      </tr>
      <tr>
        <th>Team</th>
        <th>P</th>
        <th>W</th>
        <th>D</th>
        <th>L</th>
        <th>F</th>
        <th>A</th>
        <th>Pts</th>
      </tr>
    </thead>
    <tbody>
      <tr>
        <td></td>
        <td></td>
        <td></td>
        <td></td>
        <td></td>
        <td></td>
        <td></td>
        <td></td>
      </tr>
    </tbody>
  </table>
</div>

【讨论】:

    【解决方案2】:

    再次感谢 cmets 和一些进一步的谷歌搜索,以下会在更新之前删除表,除非有更好的方法?

    for(var i = standings.rows.length - 1; i >= 0; i--)
    {
        standings.deleteRow(i);
    }
    

    祝大家好运! :)

    【讨论】:

      猜你喜欢
      • 2013-03-17
      • 2021-11-27
      • 2016-10-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-16
      • 2015-07-06
      相关资源
      最近更新 更多