如何将随机整数放入HTML和JS中的表中

时间:2018-08-03 08:25:32

标签: javascript html math

我需要HTML表格中的随机整数,并且具有正确的代码,但是由于某些原因,它不起作用!到目前为止,这是我的代码:

document.getElementById(Example).innerHTML = Math.floor(Math.random() * 13)  + 1;

我的错误消息: https://i.stack.imgur.com/OhR8X.jpg 我的代码: https://i.stack.imgur.com/ji2lL.jpg

8 个答案:

答案 0 :(得分:3)

如果您为表格单元格分配一个有效的ID,则您的代码应该可以正常工作

document.getElementById("example").innerHTML = Math.floor(Math.random() * 13)  + 1;
<table>
  <tr>
    <td id="example"></td>
  </tr>
</table>

答案 1 :(得分:1)

您必须有这样的东西。

正如CodeF0x所说的那样,获取元素时必须在ID中包含'example'"example"

document.getElementById('example').innerHTML = Math.floor(Math.random() * 13) + 1;
<div id="example"></div>

答案 2 :(得分:1)

如果您的html标记是<input type='text' id='example'/>

document.getElementById("example").value = Math.floor(Math.random() * 13)  + 1;

如果您的html标记是<td id='example'></td>

document.getElementById("example").innerHTML = Math.floor(Math.random() * 13)  + 1;

document.getElementById("example").value = Math.floor(Math.random() * 13)  + 1;

document.getElementById("exampleTd").innerHTML = Math.floor(Math.random() * 13)  + 1;
<input type='text' id='example'/>

<table>
  <tr><td id='exampleTd'></td></tr>
</table>

答案 3 :(得分:0)

以下是使用您必须生成随机数的代码的示例。

Dim xlApp As New Excel.Application
xlApp.Visible = True
xlApp.UserControl = True

Dim book As Excel.Workbook
Set book = xlApp.Workbooks.Add
book.Worksheets(1).Range("A1").CopyFromRecordset rs
book.SaveAs "C:\path\to\output\file.xlsx"
var cell = document.getElementById('random');

cell.innerHTML = Math.floor(Math.random() * 13) + 1

答案 4 :(得分:0)

如果直接使用ID,或者可以将其放在变量中并以这种方式使用,则应使用ID:

<ckeditor:ckeditorcontrol runat="server" id="txt" name="" width="870" ClientIDMode="Static"></ckeditor:ckeditorcontrol>

答案 5 :(得分:0)

下面是带有列表的示例

<body>
 <ul id="myList">

 </ul>

 <button id="btn" onclick="addRandomNumber()">Add number</button>
</body>

脚本

   function addRandomNumber(){
    var randomNum = Math.floor(Math.random() * 13)  + 1;

    var node = document.createElement("LI");
    var textnode = document.createTextNode(randomNum);
    node.appendChild(textnode);
    document.getElementById("myList").appendChild(node);

  }

答案 6 :(得分:0)

typeError:无法将属性“ innerHtml”设置为空

找不到元素“示例”,因为您在Html标签之前编写了脚本

答案 7 :(得分:0)

document.getElementById("pointsA1").innerHTML = Math.floor(Math.random() * 13)  + 1;
<table>
  <tr>
    <th>Country</th>
    <th>Points</th>
  </tr>
  <tr>
    <td>England</td>
    <td id="pointsA1"></td>
  </tr>
</table>