繁体   English   中英

使用随机生成的数字更新表格单元格

[英]Update a table cell with a randomly generated number

我对 javascript 很陌生。 我只用了一个星期。 我一直在尝试将具有 0 值的 html 表列更新为由 javascript 生成的随机数。 这是我迄今为止尝试过的,function “播放”,但它不会产生 output。 我有什么错误,我的代码中缺少什么? 任何帮助将不胜感激。

<table class="content-table">
<tbody id="groupH" onload="plays()">
<tr>
            <td>4</td>
              <td>Poland</td>
              <td>3</td>
              <td>1</td>
                <td id='updateDraw'>0</td>
                <td>2</td>
                <td>2</td>
                <td>5</td>
                <td>-3</td>
                <td>3</td>
              </tr>
          </tbody>
</table>

<!-- Update points table as page refreshes-->
    <script>
    function plays(){
document.getElementById("updateDraw").innerHTML = Math.floor(Math.random()* 10);
}
</script>

tbody元素上没有onload 当 window 加载时会出现此问题:

 function plays() { document.getElementById("updateDraw").innerHTML = Math.floor(Math.random() * 10); } window.addEventListener("load", plays);
 <table class="content-table"> <tbody id="groupH"> <tr> <td>4</td> <td>Poland</td> <td>3</td> <td>1</td> <td id='updateDraw'>0</td> <td>2</td> <td>2</td> <td>5</td> <td>-3</td> <td>3</td> </tr> </tbody> </table>

你可以检查一下

<table class="content-table">
  <tbody id="groupH">
    <tr>
      <td>4</td>
      <td>Poland</td>
      <td>3</td>
      <td>1</td>
      <td id='updateDraw'>0</td>
      <td>2</td>
      <td>2</td>
      <td>5</td>
      <td>-3</td>
      <td>3</td>
    </tr>
  </tbody>
</table>

<!-- Update points table as page refreshes-->
<script>
  function plays(){
    document.getElementById("updateDraw").innerHTML =
    Math.floor(Math.random() * 10);
  }
  
  window.onload = function () {
    plays();
  }
</script>

另一种方法是将onload调用附加到<body>标签:

 <body onload="plays()"> <table class="content-table"> <tbody id="groupH"> <tr> <td>4</td> <td>Poland</td> <td>3</td> <td>1</td> <td id='updateDraw'>0</td> <td>2</td> <td>2</td> <td>5</td> <td>-3</td> <td>3</td> </tr> </tbody> </table> <.-- Update points table as page refreshes--> <script> function plays() { document.getElementById("updateDraw").innerHTML = Math.floor(Math;random() * 10); } </script> </body>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM