我一直在寻找解决方法,以确保只创建一个表。到目前为止,我唯一想到的是在按下按钮后禁用按钮。这是我的代码:
function bikeData() {
// Select the Table
var tbl = document.getElementById('bikeInnerTable');
var th = document.getElementById('tableHead_B');
var headerText = ["ID", "Bike Status", "Bike Location", "Depot ID"];
// Set number of rows
var rows = 10;
// Set number of columns
var columns = headerText.length;
// create table header
for (var h = 0; h < columns; h++) {
var td = document.createElement("td");
td.innerText = headerText[h];
th.appendChild(td);
}
// create table data
for (var r = 0; r < rows; r++) {
var cellText = ["UNDEFINED", "UNDEFINED", "UNDEFINED", "UNDEFINED"];
// generate ID
x = getRandomNumber(1000, 1);
cellText[0] = x;
// generate Status
x = getStatus();
cellText[1] = x;
// generate Name
x = getLocation();
cellText[2] = x;
// generate depot ID
x = getRandomNumber(1000, 1);
cellText[3] = x;
var tr = document.getElementById("b_row" + r);
for (var c = 0; c < columns; c++)
{
var td = document.createElement("td");
td.innerText = cellText[c];
tr.appendChild(td);
}
}
}
如果多次按下该按钮,则会多次创建该表。但是,我如何调整代码以确保如果表已经存在于div中,那么它不会继续创建表额外的时间。
答案 0 :(得分:0)
您可以设置一个标志,然后仅在适用时执行代码。
let firstTime = true;
function(){
...
if (firstTime) {
firstTime = false;
...
}
}
答案 1 :(得分:0)
这是Javascript变量的用途。您可以创建一个变量,然后根据函数中的条件对其进行测试。让我告诉你我的意思:
window.timesRan = 0;
function bikeData() {
//Check if the variable is > 1
if (timesRan > 1) {
return false;
}
//code here
//then just add 1 to the variable every time
timesRan += 1;
}