如何使用for循环创建具有不同值的按钮

How to create buttons with different value using for loop

本文关键字:按钮 何使用 for 循环 创建      更新时间:2023-09-26

所以这是我的代码。我想创建类似的按钮

随机1随机2。。。。。。。随机10

有什么方法可以用JavaScript中的for循环来实现它吗?id也是,就像第一个按钮的id是"button1"。。。。

<script type="text/javascript">
<!--
  var i = 0;
  var x = new Array(11);
  var y = new Array(11);
  for (i=1; i<=10; i++)
  {
  x[i] = 35.38825899+Math.random()*0.007962;
  y[i] = 0.03903201/0.007962*x;
  document.write('<input type="button" value="Random" onclick="sfcshonan()"/>'+'<br />');
  }
//-->
</script>

简单。更改:

value="Random"

收件人:

value="Random ' + i + '"

最终代码

document.write('<input type="button" id="button'+i+'" value="Random'+i+'" onclick="sfcshonan()"/>'+'<br />');
document.write('<input type="button" value="Random '+i+'" onclick="sfcshonan()"/>'+'<br />');
document.write('<input type="button" value="Random" onclick="sfcshonan()"/>'+'<br />');

document.write('<input type="button" id="button' + i + 'value="Random' + i + '" onclick="sfcshonan()"/>'+'<br />');


或者使用jQuery

var button = $("<input>").attr("type", "button").attr("id", "button" + i).val("Random" + i).click(sfcshonan)
$(document).append(button)

试试这个

   document.write('<input type="button" id="button'+i+'" value="Random'+i+'" onclick="sfcshonan()"/>'+'<br />');

说明

   document.write('<input type="button" value="Random" onclick="sfcshonan()"/>'+'<br />');