问题
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.
Any help?
<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--;
}
});
});
回答1:
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.
So instead of
$("#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++;
});
you would have:
$("#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++;
});
来源:https://stackoverflow.com/questions/28172872/javascript-random-number-in-function-onclick