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

时间:2013-05-16 06:34:27

标签: javascript

所以这是我的代码。 我想创建像

这样的按钮

随机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>

4 个答案:

答案 0 :(得分:0)

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)

答案 1 :(得分:0)

试试这个

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

而不是

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

答案 2 :(得分:0)

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

答案 3 :(得分:0)

简单。改变:

value="Random"

要:

value="Random ' + i + '"

最终代码

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