我在mousedown事件上无法从1-100生成10个随机整数。另外,我还需要在表格行中显示它们,我是计算机编程的新手,而且我不知道自己犯了什么错误。
这是我的代码:
function process() {
'use strict';
var ara = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
var index;
var output = '<tr>';
for (var i = 0; i < 1 0; i++) {
index = Math.floor(Math.random() * 100);
output += '<td>' + ara[index] + '</td>';
}
output += '</tr>';
document.getElementById('numbers').innerHtML = output;
}
function init() {
'use strict';
document.getElementById('showarray').onmousedown = process;
} // End of init() function
window.onload = init;
ID号是一个表格标签
id show array是H3标签,我必须单击以获取10个整数
这是HTML
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>assignment2.html</title>
<!--[if lt IE 9]>
<script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
<link rel="stylesheet" href="css/styles.css">
</head>
<body>
<!-- assignment2.html -->
<h2>10 Random Integers from 1 to 100</h2>
<h3 id='showarray'>Mouse down here to show integers in table below</h3>
<table id="numbers" border="2"></table>
<span id="show5th">The fifth element is ?</span>
<script src="js/assignment2.js"></script>
</body>
</html>
固定了
10
和innerHTML
的jsfiddle 最佳答案
从1到100产生10个随机数;
var numbers = [];
while (numbers.length <10) {
// ParseInt for rounding. Real random numbers are 99 starting on 1.
var number = parseInt(Math.random() * 99)+1,10);
// save the number into an array and avoid duplicated.
if (numbers.indexOf(number) === -1 ) {
numbers.push(number);
}
}
在表格单元格中显示数字
如果您使用的是jQuery,这将很容易。
// creates table row element
var row = $('<tr>');
$.each(numbers, function(i) {
// creates new table cell element
var cell = $('<td>');
cell.text(i);
// append cell into row without inserting into the DOM.
cell.append(row);
});
// appends the resulting row and it's content into the DOM element with an id of `#target`
$('#target').append(row);
如果您不使用jQuery,则可以将此代码与Xotic提供的代码混合使用
要使其在mousedown上发生
我使用click,但是如果您确实需要mousedown,请根据需要进行更改。
将上面的代码包装为2个函数,假设:
var generateRandomNumbers = function () {
var numbers = [];
while (numbers.length <10) {
var number = Math.ceil(Math.random() * 100);
if (numbers.indexOf(number) === -1 ) {
numbers.push(number);
}
}
return numbers;
}
var appendNumbersToDom(numbers, target) {
// you may want to check for non valid paramenters here
var row = $('<tr>';
$.each(numbers, function(i) {
var cell = $('<td>');
cell.text(i);
cell.append(row);
});
$(target).append(row); }
和来电者
$('#showarray').on('click', function() {
appendNumbersToDom(generateRandomNumbers, '#target');
});