函数onclick中的Javascript随机数 [英] Javascript random number in function onclick

查看:282
本文介绍了函数onclick中的Javascript随机数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

需要一些帮助。用下面的javascript。在插入一行时,我需要随机数t来在每次点击(插入)时生成一个新数字。我必须将每一行作为数组发送到处理器,因此每个插入时需要一个唯一的数字。我可以让它第一次工作,但当然它只是在负载而不是每次点击产生。经过几个小时试图弄明白......但没有骰子。

Need some help. with the below javascript. On inserting a row I need the random number t to generate a new number on each click (insert). I have to send each row to the processor as an array so that needs to be a unique number on each insert. I can get it to work the first time but of course it's just generating on load and not each click. Been at it for hours trying to figure it out... but no dice.

任何帮助?

<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。你需要做的是在click函数中生成数字,这样

You are correct that you are only generating the random number on page load, because you define t right when the page loads. What you need to do is generate the number inside the click function, so that way

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

每次点击时都会调用

,而不是在文档准备就绪时调用一次。

is called every time you click instead of just once when the document is ready.

所以代替

 $("#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++;

});

这篇关于函数onclick中的Javascript随机数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆