簡體   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