У меня есть функция, которая создает таблицу и выбирает три случайных значения из массива для заполнения таблицы (см. Код).
Проблема: Вместо того, чтобы выбирать три новых значения, функция просто добавляет вниз и создает большую таблицу.
Цель: Создать функцию, чтобы я мог получить 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;
}
Извините, если код немного длинный, я просто хотел, чтобы тот, кто читает это, точно знал, что я делаю. Я уверен, что часть кода не имеет отношения.