我在 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 数组是我必须单击才能获取 10 个整数的 H3 标签
这是 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>
jsfiddle已修复 10
和 innerHTML
最佳答案
生成 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 提供的代码混合使用
让它在鼠标按下时发生 我使用了 click,但如果您确实需要 mousedown,请根据需要更改它。
将上面的代码包装成两个函数,比方说:
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');
});
关于javascript - 在 mousedown 事件上生成 1-100 之间的 10 个随机整数时遇到问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18555427/