我有一个创建表的功能,并从数组中选择三个随机值来填充表(请参见代码)。
问题:该函数无需选择三个新值,而只是将其添加到底部并创建一个更大的表。
目标:创建函数,以便获得3个随机数组元素,然后重新运行选择3个新元素来替换3个旧元素的函数!
HTML
<table border="1" id = 'hi'>
<tr>
<th id = 'replace' onclick="getTable(); myFunction();">Find Workout</th>
</table>
JS
var workouts = ['situps', 'planks', 'hollow rock', 'bicycle', 'L2S']
//Setting a copy of the array to be manipulated
var copy = workouts.slice();
//Prepping the table before the loop so it can be filled in with values
var table = '';
for(var j = 0; j < 3; j++)
{
//Setting a variable to be a random integer between 1 and 3, then
saving that in a new variable.
//That new variable, answer, plugs the value received into the array to
get one of the indexes of the array
var random = Math.floor(Math.random() * copy.length);
var answer = copy[random];
table += '<tr>';
table += '<td>';
table += answer;
table += '</td>';
table += '</tr>';
//Removing the selected item so it wont show again
copy.splice(random, 1);
}
//Runs the function to create the table
function getTable() {
document.getElementById('hi').innerHTML += ('<table border = 1>' +
table + '</table>');
}
//Replace "Find Workout" with "Recycle" indicating you can recycle to
get different workouts
function myFunction() {
var str = document.getElementById('replace').innerHTML;
var res = str.replace("Find Workout", "Recycle");
document.getElementById("replace").innerHTML = res;
}
很抱歉,如果代码有点长,我只是想让读过此书的人确切知道我在做什么。我确定其中一些代码不相关。