【问题标题】:Javascript random number in function onclick函数onclick中的Javascript随机数
【发布时间】:2015-03-26 05:00:55
【问题描述】:

需要帮助。使用下面的 javascript。在插入一行时,我需要随机数 t 在每次点击(插入)时生成一个新数字。我必须将每一行作为一个数组发送到处理器,以便每个插入都需要一个唯一的数字。我可以让它第一次工作,但当然它只是在加载时生成,而不是每次点击。花了好几个小时试图弄清楚...但没有骰子。

有什么帮助吗?

<script type="text/javascript">
     $(document).ready(function(){
     var i=1;
     var t = Math.floor(Math.random() * 256);

      $("#add_row").click(function(){
      $('#addr'+i).html("<td>"+ (i+1) +"</td><td><input name='need["+t+"][type]' type='text' placeholder='Name' class='form-control input-md'  /> </td><td><input  name='need["+t+"][scope]' type='text' placeholder='Mail'  class='form-control input-md'></td><td><input  name='need["+t+"][priority]' type='text' placeholder='Mobile'  class='form-control input-md'></td>");

      $('#tab_logic').append('<tr id="addr'+(i+1)+'"></tr>');
      i++;
  });
     $("#delete_row").click(function(){
     if(i>1){
         $("#addr"+(i-1)).html('');
         i--;
         }
     });

  });

【问题讨论】:

  • 你为什么不把随机数生成放在你的点击函数中呢?因为现在,由于关闭,t 变量将在页面加载完成时实例化一次。
  • 谢谢bmartin!!!像魅力一样工作!

标签: javascript insert html-table onclick row


【解决方案1】:

您是正确的,您只在页面加载时生成随机数,因为您在页面加载时正确定义了 t。你需要做的是在click函数里面生成数字,这样就可以了

var t = Math.floor(Math.random() * 256);

在您每次单击时调用,而不是在文档准备好时调用一次。

所以不是

 $("#add_row").click(function(){
  $('#addr'+i).html("<td>"+ (i+1) +"</td><td><input name='need["+t+"][type]' type='text' placeholder='Name' class='form-control input-md'  /> </td><td><input  name='need["+t+"][scope]' type='text' placeholder='Mail'  class='form-control input-md'></td><td><input  name='need["+t+"][priority]' type='text' placeholder='Mobile'  class='form-control input-md'></td>");

  $('#tab_logic').append('<tr id="addr'+(i+1)+'"></tr>');
  i++;

});

你会:

 $("#add_row").click(function(){
  var t = Math.floor(Math.random() * 256);
  $('#addr'+i).html("<td>"+ (i+1) +"</td><td><input name='need["+t+"][type]' type='text' placeholder='Name' class='form-control input-md'  /> </td><td><input  name='need["+t+"][scope]' type='text' placeholder='Mail'  class='form-control input-md'></td><td><input  name='need["+t+"][priority]' type='text' placeholder='Mobile'  class='form-control input-md'></td>");

  $('#tab_logic').append('<tr id="addr'+(i+1)+'"></tr>');
  i++;

});

【讨论】:

  • 是的。这种事情叫做闭包closure
猜你喜欢
  • 1970-01-01
  • 2013-05-28
  • 1970-01-01
  • 1970-01-01
  • 2016-11-03
  • 2021-06-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多